Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

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

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(SpringRunner.class) . Does using @RunWith(SpringRunner.class) has any advantages over using @RunWith(MockitoJUnitRunner.class)? Can i still use feature like @Injectmock, @Mock, @Spy with @RunWith(SpringRunner.class)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The SpringRunner provides support for loading a Spring ApplicationContext and having beans @Autowired into your test instance. It actually does a whole lot more than that (covered in the Spring Reference Manual), but that's the basic idea.

Whereas, the MockitoJUnitRunner provides support for creating mocks and spies with Mockito.

However, with JUnit 4, you can only use one Runner at a time.

Thus, if you want to use support from Spring and Mockito simultaneously, you can only pick one of those runners.

But you're in luck since both Spring and Mockito provide rules in addition to runners.

For example, you can use the Spring runner with the Mockito rule as follows.

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Mock
    MyService myService;

    // ...
}

Though, typically, if you're using Spring Boot and need to mock a bean from the Spring ApplicationContext you would then use Spring Boot's @MockBean support instead of simply @Mock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...