0

and thank you in advance for any and all your assistance.

I have a method that I'm trying to test.

Within this method is a call to UserMembership.Validate() //custom override but the code isn't functional yet and is outside the scope of the test.

I want to therefore mock (using moq) the return result so that the actual test of the method can succeed.

Here is the code

public LoginResponse Login(LoginRequest request)
{
    var response = new LoginResponse(request.RequestId);

    // Validate client tag and access token
    if (!ValidateRequest(request, response, Validate.ClientTag | Validate.AccessToken))
        return response;

    if (!UserMembership.ValidateUser(request.UserName, request.Password))
    {
        response.Acknowledge = AcknowledgeType.Failure;
        response.Messages = "Invalid username and/or password.";
        //response.MessageCode = -4;
        return response;
    }

    _userName = request.UserName;

    return response;
}

So, my test is for LoginResponse() but I want to 'fake' the UserMembership return value (bool) to true...

Simple enough I'm sure for you guys.

TIA, Hugh.

Hugh
  • 1
  • 1

2 Answers2

1

You could probably re-title your question to "How do you use a mocking framework with unit testing 99% of the time," because you're right on track for doing just that - a very typical usage.

You're going to want to extract an interface from your UserMembership class (right click inside the class, select "refactor" and then "extract interface."), then use Moq to create mock instances of that interface for use within your tests. Then you can use Moq to "setup" the behavior of that mock to do anything you want it to during your test. The syntax would look like this:

var userMembershipMock = new Mock<IUserMembership>();
userMembershipMock.Setup(m=> m.ValidateUser(It.Is<string>(str=> str == "myUserName"), It.Is<string>(str=> str == "myPassword"))).Returns(true);

Then you would create a new instance of your class, passing in your mock instance of IUserMembership (but since you'll make your class's constructor takes an argument of the interface type, your class won't care whether you're passing it a mock or an actual UserMembership instance

 MyClass myClass = new MyClass(userMembershipMock.Object);

after which you could begin actually testing the behavior of your MyClass:

var request = new LoginRequest { UserName = "myUserName", Password = "myPassword" };
LoginResponse response = myClass.Login(request);

And then you can assert that your class's response is what you expect:

Assert.AreEqual(AcknowledgeType.Success, response.Acknowledge);

or you can verify that your mock's method (or property) was invoked as you expected:

userMembershipMock.Verify(m=> m.ValidateUser(It.Is<string>(str=> str == "myUserName"), It.Is<string>(str=> str == "myPassword")), Times.Once());

and so on.

The Moq quick start page is kind of sort of a one-page read, and can teach you 99% of everything that you need to know to use it.

0

The only way I can think of to mock UserMembership in this case (assuming it's not a property) is to use an IoC framework like Castle Windsor or Ninject. When you use an IoC container you would refactor your calls to UserMembership into an interface (IUserMembership) and use the container to provide an implementation:

if (Container.Resolve<IUserMembership>().ValidateUser(request.UserName, request.Password))

Then in your unit test Setup you would register the implementation of IUserMembership to be the mock object:

var mock = new Mock<IUserMembership>();
Container.Register<IUserMemberhip>().Instance(mock.Object);

You would have to also create a production implementation. If this is the standard UserMembership class, this implementation will probably do nothing other than UserMembership. Although, there are other ways to mimic this kind of duck typing.

kelloti
  • 8,705
  • 5
  • 46
  • 82
  • Hi Kelloti, thank you for your reply. That's what I figured too, and why I used the Custom Membership in my example because it's not really one of those classes that tend to have an interface easily fakeable for Castle. I guess what I'm trying to get at is how to test Membership without the database requests, and trying to learn more about Mocking... which I'm not up-to-speed with except for the more generic functions for testing. I look forward to see if any other replies come back regarding Mocks. Thank you again, Hugh – Hugh Jan 25 '11 at 15:51
  • Yes, it's a bit of a complicated topic and I don't have any especially good articles for you. We often need this pattern when mocking .NET framework classes. I think your stumbling block is that this requires some redundant work - you have to create a dumb class whose only purpose is to call the methods of UserMembership. Fortunately someone (http://www.claassen.net/geek/blog/tag/castle) has already come up with an automated solution to make this easy. – kelloti Jan 26 '11 at 06:44
  • 1
    I have come to agree with the post http://stackoverflow.com/questions/1465849/using-ioc-for-unit-testing that it's best to keep your IoC configuration away from your unit tests, so that you can focus on creating mocks only for the dependencies that are directly required by the code you're testing, and by doing so you avoid coupling your unit tests to your IoC framework, and you also avoid the possibility of having to configure some deep hierarchy of unneeded nested dependencies just to get individual tests to run. –  Feb 11 '12 at 17:48
  • @ardave - in the year since I wrote this answer, I've come to agree with you completely. Mixing IoC configuration with unit tests causes more pain due to over coupled layers than the benefits its supposed to have. Upvote this comment if I should delete my answer. – kelloti Feb 12 '12 at 18:04
  • Tough call, Kelloti. It's up to you. I recognized this particular decision point (IoC in testing) as soon as I encountered it, but it was some while after that before I was able to recognize any reasons for choosing one way or the other. –  Feb 13 '12 at 13:01