junit 测试springMVC的Controller、Service层代码

时间:2023-01-22 10:29:42

用junit对springMVC的Controller(Service同理)进行测试

注解的方式

java代码:
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:/spring-servlet.xml")
public class ControllerTestFirst {
@Autowired
private YourController yourController;

@Test
public void yourTest(){
yourController.yourMethod();
}
}

需要导入的包:
   以下是maven的pom.xml文件内容,若包的版本不正确,不互相匹配,可能执行会报错。以下引入的包作为参考。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.hxj.TestCode</groupId>
<artifactId>test_code</artifactId>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.4.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>


直接用java代码的方式

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class ControllerTestSecond {
@Test
public void yourTest(){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-servlet.xml");
// ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-servlet.xml");
YourController yourController = ac.getBean(YourController.class);
yourController.yourMethod();
}
}

ApplicationContext ac = new ClassPathXmlApplicationContext("spring-servlet.xml");
ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-servlet.xml");

这两种方式都可以读取Spring应用上下文,读取的都是classpath(WEB-INF/classes)路径下的文件。


classpath 和 classpath* 区别:

classpath:只会到class路径中查找找文件;

classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。
优先级: lib>classes