Create a unit test for a EF repository query. As we all know unit tests are infrastructure agnostic and therefore have no kowledge of for example external services, databases, etc. So how can we create a unit test for a repository query without hitting the DB? Mocked DbSet to the rescue:

Solution:

Create an extension method on collections that can be used to mock the data/collections returned by EF instead of hitting the DB.

//A List of allocations for a gas system that we want to return when the EF LINQ query is executed

var allocationVOMockDbSet = new List<AllocationVO>

{

new AllocationVO

{

LocationId = -1,

ContractId = -1,

NominationId = null,

AllocatedQuantity = 1000,

AdjustmentIndicatorType = AdjustmentIndicatorType.Measurement,

GasDayId = -100,

GasDay = new GasDay(null, DateTime.Today),

AccountingPeriod = new YearMonth(2016, 10)

},

//new

new AllocationVO

{

LocationId = -1,

ContractId = -1,

NominationId = null,

AllocatedQuantity = 1500,

AdjustmentIndicatorType = AdjustmentIndicatorType.Other,

GasDayId = -100,

GasDay = new GasDay(null, DateTime.Today),

AccountingPeriod = new YearMonth(2016, 10)

},

}

.AsMockDbSet(); //here we define the list as a mocked set

//Now we use the StructureMap container to create an inject the DbContext of IAfterFlowContext