【问题标题】:Rhino Mocks Testing Lambda ExpressionRhino 模拟测试 Lambda 表达式
【发布时间】:2014-11-07 20:38:44
【问题描述】:

我想确保 lambda 中的表达式与预期的表达式相同

我也想为期望值写测试用例

如果我写匹配它不起作用

例如

public bool IsUserActive(User user)
{
    userRepository.Any(x=>x.UserId== user.UserId && x.IsActive);
}

单元测试用例

userRepository.Stub(x=>x.IsActive(Arg<User>.Matches(y=>y.IsActive)).Return(true);

上面的表达式不起作用

我已经看过这个例子,但我想通过检查条件来测试一些返回 bool 的 lambda 表达式

不是用户名字符串

stubUserRepository.Stub(x =>
  x.GetUserByName(Arg<string>.Matches(y =>
    y.StartsWith("aye", StringComparison.InvariantCulture) 
      || y.StartsWith("stein", StringComparison.InvariantCulture)))
  .Return(theUser);
Assert.AreSame(theUser, stubUserRepository.GetUserByName("steinegger"));
Assert.AreSame(theUser, stubUserRepository.GetUserByName("ayende"));

【问题讨论】:

  • 而不是断言 lambda 与您期望的 lambda 完全匹配,您应该测试该方法是否输出您对每种不同类型输入的期望值。测试编写的代码是您编写的代码并不是特别有效。

标签: c# unit-testing lambda rhino-mocks


【解决方案1】:

使用 AbstractConstraint 属性

public class UserConstraint :AbstractConstraint

并覆盖 Equal 以匹配约束

  _dataSericeValidator.AssertWasCalled(
                x =>
                    x.ValidateRequestUser(Arg<UserDto>.Matches(new UserConstraint (_userDto))));

【讨论】:

    猜你喜欢
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    相关资源
    最近更新 更多