一个大功能需要写很久才能完成,目前功能只完成了一部分,如何快速测试这个功能类?不需要启动服务器,也不需要专门写个请求去调用这个功能类,只需要写一个测试就可以直接调用自己的功能类来查看功能是否正确运行。
首先先展示一下我的项目结构(就是普通maven项目的结构):
- src
- main
- java
- resources
- test
- java
- main
对于springframework框架
然后在 src/test/java 目录下新建一个测试类,代码如下
package com.test;
import com.admin.mapper.PictureBaseService;
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)
//引入sqringBean配置文件
//可以直接在()中输入"classpath*:*.xml"来引入全部文件
//注意:该路径不是基于 /src/main/resources
// 而是基于 /target/classes
//也就是编译后配置文件的位置,不是编译前配置文件的位置。
@ContextConfiguration({
"classpath:/spring/activity_ac.xml",
"classpath:/application_asyn.xml",
"classpath:/application_ac.xml"})
//可以通过调整文件顺序来调整bean的加载顺序。
public class MapperTest
{
@Resource
//获取被springBean加载好的要测试的类。
private PictureBaseService service;
@BeforeClass
//在加载bean和运行@tast方法之前运行的方法,可以不要。
public static void buildConfig() { }
@Test
public void main()
{
//被@Test标注的方法可以直接运行
//运行要测试的方法
System.out.println(service.getId());
}
}
对于spring boot框架
package com.test;
import com.admin.mapper.PictureBaseService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ImportResource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
// 与上面的框架相比,就这三行行不一样
@ImportResource("classpath:root-context.xml")
@SpringBootTest
@RunWith(SpringRunner.class)
public class MapperTest
{
@Resource
//获取被springBean加载好的要测试的类。
private PictureBaseService service;
@Test
public void main()
{
//被@Test标注的方法可以直接运行
//运行要测试的方法
System.out.println(service.getId());
}
}