【问题标题】:RhinoMocks/AssertWasCalled: verifying argument length?RhinoMocks/AssertWasCalled:验证参数长度?
【发布时间】:2010-12-06 16:28:16
【问题描述】:

我的 MSpec 测试将断言使用(至少)给定长度的参数调用给定方法。

尽管参数(在运行时)的长度为 534,但此语法未通过断言:

_foo.AssertWasCalled(x => x.Write(Arg.Text.Like(".{512,}")));

ExpectationViolationException: IFoo.Write(like ".{512,}");预期 #1,实际 #0。

我对 Like() 的模式做错了什么?

【问题讨论】:

    标签: c# design-patterns arguments rhino-mocks


    【解决方案1】:

    可能与您使用的 RhinoMocks 版本有关?我正在使用 RhinoMocks 版本 3.5.0.1337 并且 Like 可以正确检测长度。

    public interface IFoo
    {
        void Write(string value);
    }
    
    public class Bar
    {
        private readonly IFoo _foo;
    
        public Bar(IFoo foo)
        {
            _foo = foo;
        }
        public void Save(string value)
        {
            _foo.Write(value);
        }
    }
    

    测试

    private Bar _bar;
    private IFoo _foo;
    
    
    [SetUp]
    public void BeforeEachTest()
    {
        var mocker = new RhinoAutoMocker<Bar>();
        _bar = mocker.ClassUnderTest;
        _foo = mocker.Get<IFoo>();
    }
    
    
    [Test]
    public void Given_input_length_equal_to_that_required_by_Like()
    {
        CallSave("".PadLeft(512));
    }
    
    [Test]
    public void Given_input_longer_than_required_by_Like()
    {
        CallSave("".PadLeft(513));
    }
    
    [Test]
    [ExpectedException(typeof(ExpectationViolationException))]
    public void Given_input_shorter_than_required_by_Like()
    {
        CallSave("".PadLeft(511));
    }
    
    private void CallSave(string value)
    {
        _bar.Save(value);
        _foo.AssertWasCalled(x => x.Write(Arg.Text.Like(".{512,}")));
    }
    

    顺便说一句,如果我使用 .Expect() 而不是 .AssertWasCalled(),测试也会通过。

    private void CallSave(string value)
    {
        _foo.Expect(x => x.Write(Arg.Text.Like(".{512,}")));
        _bar.Save(value);
        _foo.VerifyAllExpectations();
    }
    

    如果您通过了这些测试并且您确定参数的长度,则通过将测试更改为来验证 Write 是否被调用

    _foo.AssertWasCalled(x => x.Write(Arg<specify type here>.Is.Anything))
    

    编辑:

    RhinoMocks 3.6.0.0 版也通过了测试

    【讨论】:

    • 我在断言中使用了 Like 而不是我的上下文/设置。我根据您的代码安排了一些事情,我的代码现在按预期工作。非常感谢。
    【解决方案2】:

    为什么不直接测试争论的长度

     Assert.IsTrue(Arg.Text.Length >= 512);
    

    通常在 Rhino 模拟中,当您得到“预期 #1,实际 #0”时。这意味着 Equals 存在问题,例如没有在对象上实现 equals。

    【讨论】:

    • 我对 Arg.Text 的理解是它只在 AssertWasCalled() 调用期间可用?
    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2017-02-25
    • 1970-01-01
    • 2021-08-09
    • 2021-11-22
    相关资源
    最近更新 更多