2

I'm trying to mock a Userservice that inherits a baseclass with som generic methods. I'm not able to mock the call to RetrieveEntitiesTest.

When I call var validated = _userServiceMock.Object.ValidateUser(email, password); the acctual implementation of RetrieveEntitiesTest is executed...

Is this possible? U can se a representation of my code below:

public class BaseService
{
    public virtual bool RetrieveEntitiesTest<T>(QueryExpression query)
    {
        return false;
    }
}

public class UserService : BaseService
{
    public bool ValidateUser(string username, string password)
    {
        // adding query parameters
        var query = new QueryExpression();

        var userCount = RetrieveEntitiesTest<User>(query);

        return userCount > 0;
    }
}

[TestFixture]
public class UserServiceTests
{
    private Mock<UserService> _userServiceMock;

    [TestFixtureSetUp]
    public void TestFixtureSetUp()
    {
        _userServiceMock = new Mock<UserService>();
    }

    [Test]
    public void ValidateLogin_ValidEmailValidPassword_ValidatedAndReturnsTrue()
    {
        string email = "user@company.com";
        string password = "password";
        var query = .....

        _userServiceMock.Setup(x => x.RetrieveEntitiesTest<User>(new QueryExpression())).Returns(true);

        var validated = _userServiceMock.Object.ValidateUser(email, password);

        Assert.IsTrue(validated);
    }
}
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
Kulvis
  • 655
  • 11
  • 33
  • possible duplicate of [Mocking a base class method call with Moq](http://stackoverflow.com/questions/1293151/mocking-a-base-class-method-call-with-moq) – the_drow Nov 29 '11 at 17:37

1 Answers1

3

Your are not correctly setting up your Mock. Use It.IsAny (see Matching Arguments section) instead of a new QueryExpression:

_userServiceMock
    .Setup(x => x.RetrieveEntitiesTest<User>(It.IsAny<QueryExpression>()))
    .Returns(true);
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • I can remove the parameter completly and it wont make any difference – Kulvis Nov 29 '11 at 17:55
  • Interesting... are you sure that your original RetrieveEntitiesTest gets called? Can you debug the test with a breakpoint in the method? Because I've created a small repro based on your code and with using the It.IsAny<> the test is green for me. – nemesv Nov 29 '11 at 18:02
  • hmm... The mothod is called and returns false. Breakpoint is hit. – Kulvis Nov 29 '11 at 18:04
  • Can you please update your post with a compiling example code? So the definition of the `User` and `QueryExpression` is interesting, and also the "var query = ....." part. And by the way in you current sample `RetrieveEntitiesTest` returns a `bool` but in your validate method `return userCount > 0;` suggests that this a `int`. – nemesv Nov 29 '11 at 18:11
  • No problem :) I'm glad that we've figured it out. – nemesv Nov 29 '11 at 18:14