New Ideas for Junit Testing
Let's take a look at the native Junit test used before, we are already familiar with it:
@Test
// 测试数据源连接
public void test1() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource dataSource = (ComboPooledDataSource) app.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
@Test
// 测试userService对象
public void test2() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) app.getBean("userService");
System.out.println(userService);
}
This design seems not so perfect:
① The new
app container must be taken out every time
② Re-use to getBean
obtain the object to be tested
Therefore, we think of a more beautiful design: through annotations, directly inject the Bean object that you want to test into the test class.
Spring integrated Junit implementation ideas
❶ Import Junit coordinates
❷ Use @RunWith to indicate that this class is running in the spring test environment
❸ Use @ContextConfiguration to specify the configuration file/configuration class
❹ Use @Autowired to inject the object you want to test
❺ Use @Test to test, generally print the object
Code demo
❶ Import Junit coordinates
<!-- 注意:如果spring是5版本及以上,junit版本必须是4.12及以上 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
❷❸❹❺ Test code design
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml") // 如果是配置文件
@ContextConfiguration(classes = {
SpringConfiguration.class}) // 如果是配置类
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test() {
System.out.println(userService);
System.out.println(dataSource);
}
}