繁体   English   中英

如何使用 Rhino Mocks 并测试一个方法没有被调用?

[英]How to use Rhino Mocks and test that a method is not called?

我有以下代码:

public class Foobar{
    public static void Go(IFoo foo){
        if (foo.bar != null){
            foo.bar.action = !foo.bar.action;
        }
    }
}

并且想测试当 foo.bar == null 时 foo.bar.action 不会改变。

我已经模拟了一个 IFoo object,但我不确定我应该如何测试 go 来测试 rest。 有什么建议么?

您可以使用VerifyGet模拟方法测试bar属性Get仅调用一次 - 这是if语句中的调用:

    [Test]
    public void Action_WasNotSet()
    {
        var mockFoo = new Mock<IFoo>();

        Foobar.Go(mockFoo.Object);

        mockFoo.VerifyGet(f => f.bar, Times.Once);
    }

注意:我假设bar是 class

if语句的计算结果为 true 时,可能会调用bar属性 3 次并且无法调用VerifyGet

如果您想明确bar属性肯定是null ,您可以添加以下模拟设置:

mockFoo.SetupGet(f => f.bar).Returns((Bar)null);

但作为 class 的默认值是null ,此设置不是必需的,但可能会使您的测试更具可读性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM