基于springframework或spring boot框架的测试方式

一个大功能需要写很久才能完成,目前功能只完成了一部分,如何快速测试这个功能类?不需要启动服务器,也不需要专门写个请求去调用这个功能类,只需要写一个测试就可以直接调用自己的功能类来查看功能是否正确运行。

首先先展示一下我的项目结构(就是普通maven项目的结构):

  • src
    • main
      • java
      • resources
    • test
      • java

对于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());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值