Note of learning JUnit
In the previous chapter, when we do test, we need to write
1 2
| ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml"); Xxxx xxx = context.getBean(xxx.class);
|
Now we want JUnit help us to create.
JUnit5
First add dependencies
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>6.0.2</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.6.3</version> </dependency>
|
Then we config the xml file and turn on component-scan.
Then we create a User class and add a method and add annotation @Component
In the Test class, we can write in this way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package org.example.junit.junit5;
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(locations = "classpath:bean.xml") public class TestJUnit5 { @Autowired private User user;
@Test public void testUser() { System.out.println(user); user.run(); } }
|
or you use the following to replace @SpringJUnitConfig
1 2
| @ExtendWith(SpringExtension.class) @ContextConfiguration("classpath:bean.xml")
|
JUnit4
add dependency
1 2 3 4 5 6
| <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
|
And then write like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package org.example.junit.junit4;
import org.example.junit.junit5.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:bean.xml") public class TestJUnit4 { @Autowired private User user;
@Test public void test() { System.out.println(user); user.run(); } }
|
Author: o_oyao
License: All articles in this blog are licensed under
CC BY-NC-SA 4.0 unless stating additionally.