Unit Testing without Assertions

后端 未结 14 2302
夕颜
夕颜 2020-12-17 08:35

Occasionally I come accross a unit test that doesn\'t Assert anything. The particular example I came across this morning was testing that a log file got written to when a co

相关标签:
14条回答
  • 2020-12-17 08:41

    I have to admit that I have never written a unit test that verified I was logging correctly. But I did think about it and came across this discussion of how it could be done with JUnit and Log4J. Its not too pretty but it looks like it would work.

    0 讨论(0)
  • 2020-12-17 08:42

    The name of the test should document this.

    void TestLogDoesNotThrowException(void) {
        log("blah blah");
    }
    

    How does the test verify if the log is written without assertion ?

    0 讨论(0)
  • 2020-12-17 08:44

    This would be the official way to do it:

    // Act
    Exception ex = Record.Exception(() => someCode());
    
    // Assert
    Assert.Null(ex);
    
    0 讨论(0)
  • 2020-12-17 08:44

    It can be a good pragmatic solution, especially if the alternative is no test at all.

    The problem is that the test would pass if all the functions called were no-ops. But sometimes it just isn't feasible to verify the side effects are what you expected. In the ideal world there would be enough time to write the checks for every test ... but I don't live there.

    The other place I've used this pattern is for embedding some performance tests in with unit tests because that was an easy way to get them run every build. The tests don't assert anything, but measure how long the test took and log that.

    0 讨论(0)
  • 2020-12-17 08:51

    I sometimes use my unit testing framework of choice (NUnit) to build methods that act as entry points into specific parts of my code. These methods are useful for profiling performance, memory consumption and resource consumption of a subset of the code.

    These methods are definitely not unit tests (even though they're marked with the [Test] attribute) and are always flagged to be ignored and explicitly documented when they're checked into source control.

    I also occasionally use these methods as entry points for the Visual Studio debugger. I use Resharper to step directly into the test and then into the code that I want to debug. These methods either don't make it as far as source control, or they acquire their very own asserts.

    My "real" unit tests are built during normal TDD cycles, and they always assert something, although not always directly - sometimes the assertions are part of the mocking framework, and sometimes I'm able to refactor similar assertions into a single method. The names of those refactored methods always start with the prefix "Assert" to make it obvious to me.

    0 讨论(0)
  • 2020-12-17 08:54

    Tests should always assert something, otherwise what are you proving and how can you consistently reproduce evidence that your code works?

    0 讨论(0)
提交回复
热议问题