【问题标题】:How to check setter is not called for a moq object如何检查最小起订量对象不调用 setter
【发布时间】:2014-01-03 09:05:07
【问题描述】:

我有一个财产。在我的单元测试中,我想确保不调用该集合。我怎样才能做到这一点?

我可以检查该值是否已设置,但我如何确保它未设置。

public ISomeInterface
{
    bool? SomeProperty { get; set; }
}


public SomeClass
{
    SomeClass(ISomeInterface someInterface)
    {    _someInterface = someInterface;    }

    public void SomeMethod(bool condition)
    {
         if (condition)
              _someInterface.SomeProperty = true;
    }
}

// Test
var moq = new Mock<ISomeInterface>();
var target = new SomeClass(moq.Object);

target.SomeMethod(false);

// Check here that someInterface.SomeProperty set is not called.
moq.VerifySet(i => i.SomePropery = true); // This checks that set is called. But how to check if it is not called?

【问题讨论】:

标签: c# unit-testing tdd moq


【解决方案1】:

moq.VerifySet(i =&gt; i.SomePropery = true,Time.Never); 应该这样做。

但我更倾向于在SUT 被执行后测试SomeProperty 的值是否为假,以便解耦实际行为(SomeProperty 不会结束 为 false,无论 如何 从实际的实现细节(SomeProperty 永远不会直接设置)。

例如,您可以稍后将代码重构为

public void SomeMethod(bool condition)
{
    _someInterface.SomeProperty = SomeOtherComponent.MakeTheDecision(condition)
}

意味着您的测试将保证失败,更糟糕的是,就_someInterface 的实际值而言将毫无意义(因为在这种情况下它总是set

注意这意味着在SomeProperty 上有一个public 访问器,您可以从测试代码中访问它;如果您不想这样做,那么您正在测试一个私有成员,这并不是单元测试的重点——您应该只测试公共实现。

只是我的 2c。

【讨论】:

    【解决方案2】:

    调用 .VerifyAll() 也可能会有所帮助:D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-22
      • 2014-11-18
      • 1970-01-01
      • 2013-05-31
      • 2016-08-24
      • 1970-01-01
      • 2022-01-13
      • 2010-09-25
      相关资源
      最近更新 更多