Skip to content

Associated with EntityFrameworkCore

NightAngell edited this page Feb 23, 2019 · 9 revisions

Knowledge from basics is required to understand this topic.

All this DbContext's (including mock by default) are lazy loaded, so don`t worry about performance. They are also auto disposed after use.

You can use this features both with HubUnitTestsWithEF<TDbContext> and HubUnitTestsWithEF<T, TDbContext>

DbContextMock

 //By default, pure TDbContext mock, without any setup.
 public Mock<TDbContext> DbContextMock;

Why this mock can be usefull?

For example we have Hub which is dependend from DbContext. However We testing method which not use that DbContext. So better not initialize entire in memory database (remember, My In memory databases are lazy loaded) when we dont need it and instead use mock (which is also lazy loaded).

DbInMemorySqlite

DbInMemorySqlite is normal DbContext (But with in Sqlite in memory provider), and you should use it as normal DbContext.

 //Relational database in memory. 
 //During instance creation it ensure if db is created.
 //https://docs.microsoft.com/pl-pl/ef/core/miscellaneous/testing/sqlite
 public TDbContext DbInMemorySqlite;

DbInMemory

DbInMemory is normal DbContext (But with in memory provider), and you should use it as normal DbContext.

 //Database in memory (not really relational). 
 //During instance creation it ensure if db is created.
 //https://docs.microsoft.com/pl-pl/ef/core/miscellaneous/testing/in-memory
 public TDbContext DbInMemory;

Example of use

 public void TestingMethod_TestScenario_ExpectedResult()
 {
     //Arrange
     //Let's assume we have table with notes
     var note = new Note { Title="Lorem", Content="Ipsum"};
     DbInMemorySqlite.Notes.Add(note);
     DbInMemorySqlite.SaveChanges();
     ...
     
     //Act
     //Assert
 }
Clone this wiki locally