How do I verify if something didn't happen?

438 views Asked by At

We are using OpenCover for our solution test coverage and I noticed that

public async Task Build(ProcessorContext context)
{
    context.ResultBetSlip.Bets.Clear();

    // Here OpenCover tells me that I need to cover two branches
    // so I assume I need to verify that GetAvailablePlugins can be empty and
    // no Build method was called.
    // How do I do that?
    foreach (var plugin in _pluginFactory.GetAvailablePlugins())
    {
        await plugin.Build(context);
    }
}

Now my test would look like that

[Test]
public async Task Build_ShouldntEnterForeachWhenThereAreNoPluginsRegistered()
{
    // Arrange
    var pluginFactoryMock = new Mock<IBetSlipProcessorServicePluginFactory>();
    var sut = new BetSlipProcessorService(pluginFactoryMock.Object);
    pluginFactoryMock
        .Setup(pf => pf.GetAvailablePlugins())
        .Returns(new List<IBetSlipProcessorServicePlugin>());

    // Act
    await sut.Build(AutoFixtureSimplified.Create<ProcessorContext>());

    // Assert
    ???
}

Should I even consider testing such case if it is possible?

EDIT:

As requested this is the test coverage report:

enter image description here

And here you can find gist of all the tests that I do in order to achieve such coverage. https://gist.github.com/kuskmen/df3f112b2b6d880741ee6ab559d64d53

1

There are 1 answers

11
Aaron Roberts On BEST ANSWER

I am assuming you are using the Moq framework for mocking. If this is the case you can do one of two things.

  1. You can create your mock in strict mode
  2. You can expect that when the plugin.Build(..) method is called that an exception is thrown.

A similar question was asked here: How to verify that method was NOT called in Moq?

edit: I simulated the exact scenario that you are seeing and I have narrowed it down to the data type that you are iterating over. Due to the fact that you are using a list I would guess there is some internal workings of the list that are causing this problem. I changed all the list references to arrays and the branch coverage returned as expected.