I’m beginner at Unit Testing. Please help me
I have class UserData UserData.cs
public partial class UserData
{
/// <summary>
/// return all not locked users
/// </summary>
/// <returns></returns>
public static List<UserData> GetAllNotLockedUsers()
{
using (var db = new VostokPortalEntities())
{
var result = db.UserData.Where(i => !i.IsLocked).ToList();
return result;
}
throw new Exception("cannot get users");
}
}
I have controller action
[HttpGet]
public ActionResult Index()
{
//get all user list
var users = UserData.GetAllNotLockedUsers();
return View(users);
}
I have method for testing
[TestMethod]
public void UserPageUnAuth()
{
var fakedHttpContext = TestCore.FakeHttpContext();
var homeController = new HomeController(fakedHttpContext);
var indexResult = homeController.Index() as ViewResult;
Assert.IsNotNull(indexResult);
}
I’d like to test this using Mock.
What should I do?
Should I rewrite class with repository pattern? Is this neccessary?
Should I rewrite controller logic?
Should I add some code to EF auto-generated classes
Are there articles in Internet about unit testing for beginners?
Is there simple way to do mocking of EF?
Moving DB operations to a Repository class is a good idea. You should start with creating an interface for the repository.
Then you should implement a non-static repository class.
Since repository is not static anymore you have to instantiate it somewhere before using it. However the code below will not be testable.
Repository is created inside the function so you can’t replace it with a mock for testing. You can inject this object using constructor injection.
Now MyController is testable because you can inject a mock instance instead of the concrete implementation.
However default controller factory will not be able to create a controller without a parameterless constructor. It doesn’t know anything about your repository implementation. From this point on, you should get the help of a DI container for creating your controllers. I will not go in detail about that, you can take a look at this blog post