开发者

MVC3 Moq account controller c# nUnit

I am trying to learn Moq but it is proving somewhat difficult.

If I want to implement some basic tests using nUnit and Moq for the account controller in a new MVC3 project, how would I go about it?

Im used to the entity framework. but not building interfaces for it.

edit: I understand the theory of it all and the 开发者_Python百科need to do it, but implementing it is confusing me

I have been using Entity Code generator (dbContext) to generate code I can use for interfaces


Ok, here is a good test: When you register a new user, you want to make sure that he will be automatically signed in the site, so he doest not need to type his username and password again.

The test would be something like this:

public void AutomaticallySignedInAfterRegistering()
{
    var membershipService = new Mock<IMembershipService>();
    var formsService = new Mock<IFormsAuthenticationService>();
    RegisterModel newUser = new RegisterModel();
    newUser.UserName = "John"
    newUser.Email = "john@somewhere.com"
    newUser.Password = "p@ss";
    newUser.ConfirmPassword = "p@ss";

    membershipService.Setup(x => x.CreateUser("John", "p@ss", "john@somewhere.com")).Returns(MembershipCreateStatus.Success);

    AccountController controller = new AccountController();
    controller.FormsService = formsService.Object;
    controller.MembershipService = membershipService.Object;

    controller.Register(newUser);

    formsService.Verify(x => x.SignIn("John", false), Times.Once());
} 

The key here is the Verify method. It works just like an Assert. In this case you are verifing that the method SignIn was called exactly once. This is an example of how to use mocks to check if the Account Controller is working as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜