这是我正在测试线路的示例if (true)
。但是,尽管条件显然是正确的,但 Moq 告诉我该方法从未被调用过。
public class test
{
public virtual void start()
{
if (true)
called();
}
public virtual void called()
{
}
}
[Test]
public void QuickTest()
{
var mock = new Mock<test>();
mock.Object.start();
mock.Verify(t => t.start(), "this works");
mock.Verify(t => t.called(), "crash here: why not called?");
}
如何测试方法调用called()
是否发生?
我认为起订量是解决方案,但从评论看来不是,所以我做了另一个例子,没有任何起订量:
public class test
{
public bool condition = true;
public test(bool cond)
{
condition = cond;
}
public virtual string start()
{
var str = "somestuff";
if (condition)
str += called();
str += "something more";
return str;
}
public virtual string called()
{
return "something more";
}
}
[Test]
public void ConditionTrue_CallsCalled()
{
var t = new test(true);
t.start();
//syntax? t.HasCalled("called");
Assert.IsTrue(result.Contains("something more"));
}
[Test]
public void ConditionFalse_NoCall()
{
var t = new test(false);
t.start();
//syntax? t.HasNotCalled("called");
// Can't check this way because something more is already being added
Assert.IsFalse(result.Contains("something more"));
}
是否有可能做到这一点?值得吗?