Search code examples
c#.netunit-testingmstest

Assert that "nothing happened" when writing unit test


When writing unit test, Is there a simple way to ensure that nothing unexpected happened ?

Since the list of possible side effect is infinite, adding tons of Assert to ensure that nothing changed at every steps seems vain and it obfuscate the purpose of the test.

I might have missed some framework feature or good practice.
I'm using C#7, .net 4.6, MSTest V1.

edit: The simpler example would be to test the setter of a viewmodel, 2 things should happen: the value should change and PropertyChanged event should be raised. These 2 things are easy to check but now I need to make sure that other properties values didn't changed, no other event was raised, the system clipboard was not touched...


Solution

  • One of the options to ensure that nothing 'bad' or unexpected happens is to ensure good practices of using dependency injection and mocking:

    [Test]
    public void TestSomething()
    {
        // Arrange
        var barMock = RhinoMocks.MockRepository.GenerateStrictMock<IBar>();
        var foo = new Foo(barMock);
        // Act
        foo.DoSomething();
        // Assert
        ...
    }
    

    In the example above if Foo accidentally touches Bar, that will result in an exception (the strict mock) and the test fails. Such approach might not be applicable in all test cases, but serves as a good addition to other potential practices.