Unit Testing without Assertions

后端 未结 14 2301
夕颜
夕颜 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 09:08

    We do this all the time. We mock our dependencies using JMock, so I guess in a sense the JMock framework is doing the assertion for us... but it goes something like this. We have a controller that we want to test:

    Class Controller {
      private Validator validator;
    
      public void control(){
        validator.validate;
      }
    
      public setValidator(Validator validator){ this.validator = validator; }
    }
    

    Now, when we test Controller we dont' want to test Validator because it has it's own tests. so we have a test with JMock just to make sure we call validate:

    public void testControlShouldCallValidate(){
      mockValidator.expects(once()).method("validate");
      controller.control;
    }
    

    And that's all, there is no "assertion" to see but when you call control and the "validate" method is not called then the JMock framework throws you an exception (something like "expected method not invoked" or something).

    We have those all over the place. It's a little backwards since you basically setup your assertion THEN make the call to the tested method.

提交回复
热议问题