spring项目如何写单元测试
一、Junit4
后台开发过程中,写单元测试是非常重要的,对于我们开发人员调试、排查问题是很方便的,
但是我们在启动项目的时候,需要将所以类交给spring托管,在单元测试中需要怎么实现类的注入呢?
直接上图
继续上代码(Junit4)
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:application-context.xml",
"classpath:application-database.xml",
"classpath:application-redis.xml"})
public class PartRelevanceTest {
@Resource
private PartRelevanceMapper partRelevanceMapper;
@Test
public void selectTypeNumOne() {
PartRelevanceTypeNum record = new PartRelevanceTypeNum();
record.setRelCode("2222112");
record.setType("2");
PartRelevanceTypeNum typeNum = partRelevanceMapper.selectTypeNumOne(record);
System.out.println(typeNum==null?"typeNum-数据为空":typeNum.toString());
}
}
原文:https://my.oschina.net/u/4269071/blog/3357680
二、Junit5
另一种测试方式(Junit5):
package com.luwanglin.controller;
import com.luwanglin.pojo.Books;
import com.luwanglin.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import java.util.List;
/**
* @author luwanglin
* @email 1769862620@qq.com
* @Date 2020/10/2 10:14
* @Version 1.0
*/
@SpringJUnitWebConfig(locations = {"classpath:applicationContext.xml"})
public class MyTestTest2 {
@Autowired
private BookService bookService1;
/*@Test
void test01() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookServiceImpl bookService = (BookServiceImpl) context.getBean("bookServiceImpl");
List<Books> list = bookService.queryAllBook();
System.out.println(list);
}*/
@Test
public void test02() {
List<Books> list = this.bookService1.queryAllBook();
System.out.println(list);
}
}
问题解决:
-
junit测试用例启动报错java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig
将servlet-api改成4.0.1的,这是因为servlet版本太低导致的,换成如下的maven依赖
<!-- servlet-jsp--> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>