滥用Moq来测试if条件

时间:2013-08-25 11:48:06

标签: c# unit-testing moq

考虑以下课程:

public class test
{
    public void start()
    {
        if (true)
            called();
    }

    internal protected virtual void called()
    {

    }
}

我想让if (true)接受测试。我最初的想法是使用Moq验证是否已调用called()。我最终得到了这个测试:

[TestFixture]
public partial class TestMethodInvocation
{
    [Test]
    public void TestWithMoqVerify()
    {
        var mock = new Mock<test>() {CallBase = true};
        mock.Object.start();
        mock.Verify(t => t.called());
    }
}

我遇到了一些麻烦,并发布了this question,我被告知不要使用Moq模拟被测试的课程。

所以我添加了一个子类并使用一个属性来测试该方法是否被调用:

public class test2 : test
{
    public bool WasCalled { get; set; }

    internal protected override void called()
    {
        WasCalled = true;
    }
}

public partial class TestMethodInvocation
{
    [Test]
    public void TestWithSubclassProperty()
    {
        var test = new test2();
        test.start();
        Assert.IsTrue(test.WasCalled);
    }
}

这两种方法都有效,但Moq实现实际上是测试代码量的一半,因为我不需要创建子类。像这样使用Moq是非常糟糕的,还是应该使用另一个框架来进行这种测试?或者这是我的代码设计中出现问题的结果?

3 个答案:

答案 0 :(得分:3)

对于是否应该为呼叫验证编写测试存在一些争议,我正试图避开它们,我宁愿测试外部行为。你要测试一些东西,看看是否达到了预期的效果,而不是进入内部。这当然不总是可行的。

现在,说完了,我打算给你一个例子(我能做的最好的方法)。假设我们有一个名为Greeter的类 - 它应该向所有stackoverflow订阅者发送恼人的SMS。现在,假设发送短信,你已经在其他地方(已经过测试和所有)编写了一些其他基础设施代码。假设此代码将是名为IMessageService的接口的实现(对不起,如果我的示例很糟糕):

public interface IMessageService
{
    void SendSMS(string message);
}

此外,假设您有SubscriberRepository可以获得所有StackOverflow订阅者。类似的东西:

public interface ISubscriberRepository
{
    IEnumerable<Subscriber> GetStackOverflowSubscribers();
}

这是您的Greeter班级:

public class Greeter
{
    private readonly IMessageService _messageService;
    private readonly ISubscriberRepository _subscriberRepository;

    public Greeter(IMessageService messageService, ISubscriberRepository subscriberRepository)
    {
        _messageService = messageService;
        _subscriberRepository = subscriberRepository;
    }

    public void SendGreetingToStackOverflow()
    {
        IEnumerable<Subscriber> stackOverflowers = _subscriberRepository.GetStackOverflowSubscribers();

        foreach (Subscriber overflower in stackOverflowers)
        {
            _messageService.SendSMS("Hello World!");
        }
    }
}

您看到它实际上正在使用IMessageService发送短信。此时,您希望(可能)测试SendSMS()被调用x次。在这种情况下,次数应与StackOverflow订阅者的数量相同。所以你的测试看起来像这样:

[Test]
public void SendGreetingToStackOverflow_CallsIMessageServiceSendSMSTwoTimes()
{
    var mockMessageService = new Mock<IMessageService>();
    var mockSubscriberRepo = new Mock<ISubscriberRepository>();

    // we will mock the repo and pretend that it returns 2 subscibers
    mockSubscriberRepo
        .Setup(x => x.GetStackOverflowSubscribers())
        .Returns(new List<Subscriber>() {new Subscriber(), new Subscriber()});

    // this is the one we're testing, all dependencies are fake
    var greeter = new Greeter(mockMessageService.Object, mockSubscriberRepo.Object);

    greeter.SendGreetingToStackOverflow();

    // was it called 2 times (for each subscriber) ?
    mockMessageService.Verify(
        x => x.SendSMS("Hello World!"),
        Times.Exactly(2));
}

再次,对不起,这可能不是最好的例子,但这是漫长的一天,这是我能想到的最好的例子:)。

我希望它有所帮助。

答案 1 :(得分:1)

一个有意义的最小例子,尽可能接近你想要做的事情:

interface Callable
{
  void Called();
}

class Test
{
  public Test(Callable x)
  {
    this.callable = callable;
  }

  public void Start()
  {
    if (true)
      callable.Called();
  }

  private Callable callable;
}

然后测试看起来像这样:

[TestFixture]
public partial class TestMethodInvocation
{
  [Test]
  public void TestWithMoqVerify()
  {
    var callableMock = new Mock<Callable>();
    var test = new Test(callableMock);
    test.Start();
    callableMock.Verify(t => t.Called());
  }
}

改述我的评论:

你不应该测试类的内部 - 测试外部行为。

答案 2 :(得分:1)

我相信您提出的真正问题是如何测试called类中test方法执行的方法?

要回答你必须问自己,“test对象在执行方法called后会有什么不同?”然后,编写单元测试,以间接方式验证对象test是否按预期方式更改。

与其他人所说的一样,Moq用于隔离对特定测试不重要的代码。在您的情况下,您不想创建模拟 - 您需要测试实际代码!

我的回答是,如果通过调用called无法查看test对象的更改方式,那么您可能需要考虑called正在做什么的逻辑。或者,您需要对test应用进一步的操作,这将显示可测试的不同状态。

例如,预期的行为可能是:

  • 如果在调用foo()后调用called()Enabled就是foo() 是的,但是
  • 如果在未调用called()的情况下调用Enabled,则foo()为false。

因此,在您的测试中,您必须在测试的类上执行多项操作(如调用var test = new test(); test.foo(); Assert(test.Enabled, Is.False); var test = new test(); test.start(); test.foo(); Assert(test.Enabled, Is.True); ),然后才能将其置于外部可测试状态:

{{1}}