I’m doing a ASP.Net MVC2 project and i want to do some unit tests on it. I tried to test my LogOnController and i have faced some difficulties. In my LogOnController I used AccountMembershipService as,
AccountMembershipService MembershipService = new AccountMembershipService();
if (MembershipService.ValidateUser(model.UserName, model.Password)){
............
..........
}
I’m using MOQ framwork and i want to know how to mock AccountMembershipService. Eventhough i have given the correct username and password “MembershipService.ValidateUser(model.UserName, model.Password)” always return false. So any one of you have a idea about how to do this..
By the way i have tried the Property injection . But all the time I got the following error..
“Invalid setup on a non-virtual (overridable in VB) member: x => x.ValidateUser(.validUserName, .validPassword)” .
It comes form the, “stubService.Setup(x => x.ValidateUser(model.UserName, model.Password)).Returns(true);”
line.
Here is my code..
[TestMethod]
public void TestLogOn_ValidUserNameAndPassword()
{
var controller = new LogOnController();
var request = new Mock<HttpRequestBase>(MockBehavior.Loose);
var model = new LogOnModel();
var context = new Mock<HttpContextBase>(MockBehavior.Loose);
var stubService = new Mock<AccountMembershipService>();
model.UserName = "xxxxx";
model.Password = "123";
context.SetupGet(x => x.Request).Returns(request.Object);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
stubService.Setup(x => x.ValidateUser(validUserName, validPassword)).Returns(true);
Assert.IsTrue(stubService.Object.ValidateUser(model.UserName, model.Password));
}
Make sure ValidateUser method virtual.
Mock the AccountMembershipService and do testing.
Your problem comes from using unoverridable method, so you should treat it as overridable.
One of solution is adding virtual keyword like the following.
Other one is defining interface and mocking the interface instead of actual AccountMembershipService class. To do this, you also need to change the DI(dependency injection) to use interface.