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

20,849

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.

Share:
20,849
Karan
Author by

Karan

Twitter: @karangb Engineer at Facebook 1st class MEng in Computer Science at Imperial College London.

Updated on July 09, 2022

Comments

  • Karan
    Karan almost 2 years

    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 = "[email protected]";
        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
    Karan almost 12 years
    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.
  • MattDavey
    MattDavey almost 12 years
    @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.