What's the actual use of 'fail' in JUnit test case?

后端 未结 8 1255
长情又很酷
长情又很酷 2021-01-30 15:31

What\'s the actual use of \'fail\' in JUnit test case?

8条回答
  •  渐次进展
    2021-01-30 15:49

    In concurrent and/or asynchronous settings, you may want to verify that certain methods (e.g. delegates, event listeners, response handlers, you name it) are not called. Mocking frameworks aside, you can call fail() in those methods to fail the tests. Expired timeouts are another natural failure condition in such scenarios.

    For example:

    final CountDownLatch latch = new CountDownLatch(1);
    
    service.asyncCall(someParameter, new ResponseHandler() {
        @Override
        public void onSuccess(SomeType result) {
            assertNotNull(result);
            // Further test assertions on the result
            latch.countDown();
        }
    
        @Override
        public void onError(Exception e) {
            fail(exception.getMessage());
            latch.countDown();
        }
    });
    
    if ( !latch.await(5, TimeUnit.SECONDS) ) {
        fail("No response after 5s");
    }
    

提交回复
热议问题