Spring和JUnit5整合及注解
-
原写法:
需要手写代码,根据配置文件加载上下文,从而得到bean,调用方法。
public class MyTest2 { @Test public void test() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); TutorService tutorService = context.getBean("tutorServiceImpl", TutorService.class); Tutor tutor = tutorService.getTutorById("20170000"); System.out.println(tutor); } }
可以使用注解简化
-
加入依赖:spring-test的版本和spring要一致。
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> <!--spring-test--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.12.RELEASE</version> <scope>test</scope> </dependency>
-
使用注解的测试类
JUnit5使用
@ExtendWith(SpringExtension.class)
*@ExtendWith和@ContextConfiguration可以合并,写复合注解@SpringJUnitConfig(locations="classpath:applicationContext.xml")
import org.junit.jupiter.api.Test;//保证这个包导入 @ExtendWith(SpringExtension.class) @ContextConfiguration("classpath:applicationContext.xml") public class MyTest { @Autowired TutorService tutorService; @Test public void test2() { Tutor tutor = tutorService.getTutorById("20170000"); System.out.println("tutor=" + tutor); } }
*JUnit4使用@Runwith(SpringJUnit4ClassRunner.class)