1 Problems and solutions in the test class
1.1 Problem
1.2 Analysis of solution ideas
2 Configuration steps
2.1 Step 1: Copy the necessary jar package for integrating junit to the lib directory
- This It should be noted that when importing a jar package, you need to import a jar package of aop in spring.
2.2 Step 2: Use @RunWith annotation to replace the original runner
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}
Copy after login
2.3 Step 3: Use @ContextConfiguration Specify the location of the spring configuration file
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
Copy after login
- @ContextConfiguration Note:
- locations attribute: used to specify the location of the configuration file. If it is on the classpath, you need to use classpath: to indicate
- classes attribute: used to specify the annotated classes. When not using xml configuration, you need to use this attribute to specify the location of the annotation class.
2.4 Step 4: Use @Autowired to inject data into the variables in the test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ;
}
Copy after login
3 Reasons for not assigning the test class to xml
- First: When a bean is configured in xml and spring loads the configuration file to create the container, the object will be created.
- Second: The test class is only used when testing functions. In the project, it does not participate in the program logic and will not solve the demand problems, so after it is created, there is no use. Then storing it in the container will cause a waste of resources.
The above is the detailed content of How to integrate Junit between Java and Spring?. For more information, please follow other related articles on the PHP Chinese website!