7

I have a test that uses System.Func expressions. It should be pretty straight forward, but the test keeps on failing.

Test:

  [TestMethod]
  public void GetUser()
  {
    var username = "john@resilientplc.com";
    var user = new User() { UserId = 1, Username = username, Password = "123456789" };

    someDataMock.Setup(s => s.GetUser(p => p.UserId == 1)).Returns(user);

    var result = userProfileModel.GetUser(user.UserId);
    Assert.AreEqual(user, result);
  }

Implementation UserProfileModel:

public User GetUser(long userId)
{
  return someDataMock.GetUser(u => u.UserId == UserId);
}

Error:

System.NotSupportedException: Unsupported expression: p => (p.UserId == 1)

Any idea where my test is incorrect?

Karan
  • 14,824
  • 24
  • 91
  • 157

1 Answers1

14

Assuming that you're using Moq and that someDataMock is a mocked object, the problem is with the setup. Try this instead...

someDataMock.Setup(s => s.GetUser(It.IsAny<Func<User, bool>>()).Returns(userProfile);

That should work, but you might want to make the mock a little bit more restrictive in what callbacks it accepts, depending on the nature of your test.

MattDavey
  • 8,897
  • 3
  • 31
  • 54
  • 1
    Yes, this works - will have to add a someDataMock.VerifyAll otherwise the test wouldnt be testing much. Still would like to make it more specific as to what the Func I send to the someDataMock. – Karan Jul 16 '12 at 10:27
  • 1
    @Newton yeh I'm not sure that it's possible to restrict the nature of Func/Action argument setups in Moq. However I would say that whichever class sends those funcs should have its own unit tests to verify that they are correct. It might not be the repositories responsibility to decide whether the callbacks it receives are correct/in context. – MattDavey Jul 16 '12 at 10:41