Spring+Junit4 for interface test example code

  • 2021-01-11 02:01:32
  • OfStack

This paper mainly studies a relevant example of Spring+Junit4 interface testing, and the specific implementation code is as follows.

1. Configuration pom. xml


<dependency> 
  <groupId>org.springframework</groupId> 
  <artifactId>spring-context</artifactId> 
  <version>4.3.2.RELEASE</version> 
</dependency> 
 
<dependency> 
  <groupId>org.springframework</groupId> 
  <artifactId>spring-test</artifactId> 
  <version>4.3.2.RELEASE</version> 
</dependency> 
 
<dependency> 
  <groupId>junit</groupId> 
  <artifactId>junit</artifactId> 
  <version>4.12</version> 
</dependency> 

2. Configuration bean

testInterface can be manually configured or automatically scanned

Manual configuration

spring profile configuration:


<bean id="testInterface" class="com.xxx.TestInterfaceImpl"> 
  </bean> 

Automatic scanning

Interface implementation class configuration


@Component 
public class TestInterfaceImpl implements TestInterface { 

spring profile configuration


<context:annotation-config/> 
 
 
  <context:component-scan base-package="com.xxx.servlet"> 
  </context:component-scan> 

3. Write interface test code


import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
 
import javax.annotation.Resource; 
 
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:applicationContext.xml") 
public class Test { 
 
  @Resource 
  TestInterface testInterface; 
 
  @Test 
  public void test1(){ 
    testInterface.test1(1,2); 
  } 

conclusion

Above is this article about Spring+Junit4 interface test example code of all content, hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: