System.NotSupportedException:不支持的表达式:p =>(p.UserProfileId == 1)

Kar*_*ran 2 c# unit-testing moq asp.net-mvc-3

我有一个使用System.Func表达式的测试.它应该非常简单,但测试仍然失败.

测试:

  [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);
  }
Run Code Online (Sandbox Code Playgroud)

实现UserProfileModel:

public User GetUser(long userId)
{
  return someDataMock.GetUser(u => u.UserId == UserId);
}
Run Code Online (Sandbox Code Playgroud)

错误:

System.NotSupportedException:不支持的表达式:p =>(p.UserId == 1)

知道我的测试不正确吗?

Mat*_*vey 8

假设您正在使用Moq并且someDataMock是一个模拟对象,问题在于设置.试试这个......

someDataMock.Setup(s => s.GetUser(It.IsAny<Func<User, bool>>()).Returns(userProfile);
Run Code Online (Sandbox Code Playgroud)

这应该可行,但您可能希望在接受的回调中使模拟更具限制性,具体取决于测试的性质.