断言调用一个方法来测试if条件 [英] Assert that a method is called to bring an if condition under test

查看:89
本文介绍了断言调用一个方法来测试if条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我测试if (true)行的示例.但是,尽管条件显然是正确的,但是Moq告诉我从未调用过该方法.

Here is an example where I am testing the line if (true). But although the condition is obviously true, Moq tells me the method was never called.

    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()的方法调用已发生?

How do I test that the method call to called() has happened?

我以为Moq是解决方案,但从评论看来似乎不是,所以我举了一个没有引用Moq的例子:

I thought Moq was the solution, but from the comments it looks like it isn't so I've made another example without any reference to Moq:

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")); 
}

是否可以这样做?值得吗?

Is it possible to do this? Is it worthwhile?

推荐答案

关于第一段代码:

mock是一个模拟对象.这意味着所有方法都将被覆盖且不执行任何操作.因此,调用mock.start()不执行任何操作并且从不调用called()是完全正常的.

mock is a mock object. That means all the methods are overridden and do nothing. So it's entirely normal that calling mock.start() doesn't do anything and called() is never called.

如果只想模拟called()并使用start()的实际实现,则需要进行部分模拟.

If you want to mock just called() and use the real implementation of start(), you need to do partial mocking.

但是我建议不要这样做,甚至建议不要尝试仅测试此类.您将测试代码与实现代码过于紧密地结合在一起.考虑做TDD:如果测试不存在,问自己,应用程序的哪些功能会中断.针对该功能编写测试,该测试应该会失败.然后编写if测试以修复测试.

But I would advise against that, I would even advise against trying to test just this class. You will couple your test code too tightly to your implementation code. Think about doing TDD: ask yourself what feature of your application breaks if that if test is not there. Write a test against that feature, which should fail. Then write the if test to fix the test.

这篇关于断言调用一个方法来测试if条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆