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

标签 c# asp.net-mvc-3 unit-testing moq

我有一个使用 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);
  }

实现 UserProfileModel:

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

错误:

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

知道我的测试哪里不正确吗?

最佳答案

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

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

这应该可行,但您可能希望根据测试的性质,使模拟在接受的回调方面更具限制性。

关于c# - System.NotSupportedException : Unsupported expression: p => (p. UserProfileId == 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11502239/

相关文章:

c# - 在 C# 中将字典作为参数传递给 Http.Post

javascript - Jest 单元测试调用返回 promise 的函数的函数

c# - 如何在 WP8.1 中更改 CheckBox 的 CheckMark 颜色?

c# - 查找文件中最后一次出现的字符串

asp.net-mvc-3 - 附加 .mdf 文件时的数据库 "cannot be opened because it is version 661"

c# - 如何设置 htmlHelpers 项目,以便它为 mvc3 和 mvc4 生成两个 dll?

python - 使 python pytest 单元测试独立于 py.test 执行的位置运行?

unit-testing - 如何从默认 "maven test"和 eclipse "run as junit test"中排除特定的单元测试

c# - 使用 Utf8Json 库序列化时排除空字段?

c# - C# 中的 XslCompiledTransform 调试