Use Moq With DbContext
Return to menu
When using Moq with DbContext open Manage Nuget Packages and install to
your Unit Test project the Moq library.
//In using block add the Moq assembly reference:
using Moq;
//Use the DbContext you know
FPC_Emp_Context FakeDbC = new FPC_Emp_Context();
var SecMocks = new Moq.Mock(FakeDbC);
Setup the Mock (Moq) Library so a method here GetEmployeesFromManagement() existing in your Controller
returns a couple of Employee objects as you knoe from the database table, like this
SecMocks.Setup(e => e.GetEmployeesFromManagement()).Returns(new List()
{
new Employee() { Alias="JohnnyMex", Name="Johnny",
ID =1, HomeEmail="johnny@mexoft.dk",
Mobile="42 52 6035", Remarks="Good for now"
},
new Employee() { Alias="RonjaRøverdatter", Name="Ronja",
ID =2, HomeEmail="ronja@roverdatter.com",
Mobile="12 34 5678", Remarks="Nobody beats Ronja"
}
});
Now you can implement the following in the Unit test:
//Here call the Moq version of GetEmployeesFromManagement method.
var t = SecMocks.Object.GetEmployeesFromManagement();
/*
here put any other code you want to test
*/
//Here test if EmployeesFromManagement() actually return a list of any Employee objects
Assert.IsTrue(t.Any());
Currently the is a drawback when the Moq object, I can't simply test a whole method that resides in the
Controller, but instead I have copy-paste the content of the method from the Controller and into the Unit test
Return to menu