Junit 5 with Spring Boot:何时使用@ExtendWith Spring或Mockito?
我有以下抽象单元测试类,我的所有具体单元测试类都扩展了它:
@ExtendWith(SpringExtension.class)
//@ExtendWith(MockitoExtension.class)
@SpringBootTest(
classes = PokerApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
public abstract class AbstractUnitTests {
@MockBean
public RoundService roundService;
@MockBean
public RoundRepository roundRepository;
}
使用 或 有什么区别?@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
我问,因为使用任何一个注释似乎都没有区别,并且两者都分别在我的代码中工作 - 允许我使用Junit5。那么,为什么两者都有效呢?
具体测试类:
@DisplayName("Test RoundService")
public class RoundsServiceTest extends AbstractUnitTests {
private static String STUB_USER_ID = "user3";
// class under test
@InjectMocks
RoundService roundService;
private Round round;
private ObjectId objectId;
@BeforeEach //note this replaces the junit 4 @Before
public void setUp() {
initMocks(this);
round = Mocks.round();
objectId = Mocks.objectId();
}
@DisplayName("Test RoundService.getAllRoundsByUserId()")
@Test
public void shouldGetRoundsByUserId() {
// setup
given(roundRepository.findByUserId(anyString())).willReturn(Collections.singletonList(round));
// call method under test
List<Round> rounds = roundService.getRoundsByUserId(STUB_USER_ID);
// asserts
assertNotNull(rounds);
assertEquals(1, rounds.size());
assertEquals("user3", rounds.get(0).userId());
}
}
相关 Build.gradle 部分 :
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.2.RELEASE'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
implementation 'junit:junit:4.12'
}
test {
useJUnitPlatform()
}