@RunWith(SpringRunner.class) vs @RunWith(MockitoJUnitRunner.class)

前端 未结 5 1807
暖寄归人
暖寄归人 2020-12-23 16:48

I was using @RunWith(MockitoJUnitRunner.class) for my junit test with mockito. But now i am working with spring boot app and trying to use @RunWith(Spring

5条回答
  •  既然无缘
    2020-12-23 17:04

    As per the JavaDoc:

    SpringRunner is an alias for the SpringJUnit4ClassRunner. To use this class, simply annotate a JUnit 4 based test class with @RunWith(SpringRunner.class). If you would like to use the Spring TestContext Framework with a runner other than this one, use org.springframework.test.context.junit4.rules.SpringClassRule and org.springframework.test.context.junit4.rules.SpringMethodRule.

    And the JavaDoc of TestContext:

    TestContext encapsulates the context in which a test is executed, agnostic of the actual testing framework in use.

    That of method getApplicationContext():

    Get the application context for this test context, possibly cached. Implementations of this method are responsible for loading the application context if the corresponding context has not already been loaded, potentially caching the context as well.

    So, SpringRunner does load the context and is responsible for maintaining it. For example, if you want to persist data into an embedded database, like H2 in-memory database, you have to use SpringRunner.class; and, to clean the tables to get rid of the records you inserted after every test, you annotate the test with @DirtiesContext to tell Spring to clean it.

    But, this is already an integration or component test. If your test is pure unit test, you don't have to load DB, or you just want to verify some method of a dependency is called, MockitoJUnit4Runner suffices. You just use @Mock as you like and Mockito.verify(...) and the test will pass. And it is a lot quicker.

    Test should be fast. As fast as possible. So whenever possible, use MockitoJUnit4Runner to speed it up.

提交回复
热议问题