Husain
Husain

Reputation: 845

Entity Framework 6 and Unit Test

I have been looking around for a solution but I couldn't find the answer (like here and here.)

public class ItemsRepository {
    public ItemDto Get(int id) {
        using (var db = new ItemContext()) {
            return db.Items.FirstOrDefault(i => i.Id == id)
                .ToDto();
        }
    }
}

I used to test this code by going all the way to the DB. I know this is not a good practice, since the unit test in this case tests the connection to the database as well.

Ideally, I want to build an in-memory database and seed it. How would I do that in this case? How do I fake ItemContext to use an in-memory list?

Note that I don't want to expose Context as a constructor, since the user will have to know about how the data is stored.

Upvotes: 1

Views: 386

Answers (1)

kat1330
kat1330

Reputation: 5322

You cannot fake ItemContext because new keyword always creates a new instance of the object. Ideally, you should inject your context by dependency injection. Something like this:

public class ItemsRepository {
    public ItemDto Get(int id) {
       return _itemContextService.Items.FirstOrDefault(i => i.Id == id)
                .ToDto();            
    }
}

In unit test _itemContextService should be injected and _itemContextService.Items should be configured with mock data. All logic which you should unit test is:

FirstOrDefault(i => i.Id == id).ToDto();            

This is only what Get(int id) method does. Connection with database is beyond of scope in unit testing this method.

Anyway, if you cannot use some DI container or somehow inject ItemContext then you can mock your connection string in unit test project.

Upvotes: 1

Related Questions