Spring boot junit5单元测试@ExtendWith无法工作
在不同的Spring Boot版本中@ExtendWith的使用也有所不同,其中在Spring boot 2.1.x之前, @SpringBootTest 需要配合@ExtendWith(SpringExtension.class)才能正常工作的。
而在Spring boot 2.1.x之后,我们查看@SpringBootTest 的代码会发现,其中已经组合了@ExtendWith(SpringExtension.class),因此,无需在进行该注解的使用了。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
public @interface SpringBootTest {
@AliasFor("properties")
String[] value() default {};
@AliasFor("value")
String[] properties() default {};
Class<?>[] classes() default {};
WebEnvironment webEnvironment() default WebEnvironment.MOCK;
enum WebEnvironment {
MOCK(false),
RANDOM_PORT(true),
DEFINED_PORT(true),
NONE(false);
…
}
}
官方也给出了相应的说明:
If you are using JUnit 4, don’t forget to also add
@RunWith(SpringRunner.class)to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there’s no need to add the equivalent@ExtendWith(SpringExtension.class)as@SpringBootTestand the other@…Testannotations are already annotated with it.
因此,在Spring Boot2.1.x之后单元测试可以简单的写成如下形式:
@SpringBootTest
public class OrderServiceTest {
@Resource
private OrderService orderService;
@Test
public void testInsert() {
Order order = new Order();
order.setOrderNo("A001");
order.setUserId(100);
orderService.insert(order);
}
}
相关文章:《SPRING BOOT JUNIT5单元测试注入BEAN抛NULLPOINTEREXCEPTION空指针异常》


关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台
除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接
本文链接:http://www.choupangxia.com/2019/11/13/spring-boot-junit5-extend-with/