Assert that a method is called to bring an if condition under test

空扰寡人 提交于 2019-12-12 01:26:03

问题


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

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

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?


回答1:


Regarding the first piece of code:

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.

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

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.



来源:https://stackoverflow.com/questions/18425163/assert-that-a-method-is-called-to-bring-an-if-condition-under-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!