SpringBoot整合测试类

磨刀不误砍材工,会用测试类总比每次重启看效果来的快和实在

测试类Junit

  • pom文件
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

这个工具类作用其实很简单,就是解决一个类中只能有一个main方法的问题。

最开始的时候测试都是写个方法,然后使用main方法调用,而有了这个专门测试类,只需要在普通的方法上面加上@Test注解即可直接右键运行

  • 使用方法
    普通的方法上面加上@Test注解即可直接右键运行
  • 使用案例
    @Test
    public void getTest(){
        System.out.println("测试类直接运行。。");
    }

有可能是@org.junit.Test注解,这个一样,是junit的包就行

SpringBoot的测试类

SpringBoot的测试类和普通的测试类不同

因为SpringBoot是基于原来的Spring、SpringMVC的整合

要想正常使用和测试,必须依赖Spring容器的支持,之前SSM是直接加载配置文件,加载容器,但是SpringBoot,如何实现加载呢?

当然SpringBoot有对应的测试jar包来测试,使用很简单,打开方式如下

  • pom
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

当然默认就会自带有junit的包。

  • 使用方法
  1. 在整合的测试类的类上面加上注解
@RunWith(SpringJUnit4ClassRunner.class)

里面的内容基本是固定的

其实直接不指定版本也可以使用

@RunWith(SpringRunner.class)
  1. 同样在类上面加注解,指定启动类
@SpringBootTest(classes = {PassWordNoteMain1996.class})

这里的启动类是自己的,这样有了SpringBoot启动器,就会对应加载Spring的容器了。

其实这里直接使用@SpringBootTest不传递参数也可以使用。

  1. 整合的类效果如下
package com.hello;

import com.hello.entities.PwNote;
import com.hello.service.PwNoteService;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;

/**
 * @author :QiuShi
 * @Date :2020/11/9 19:19
 * @Version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {PassWordNoteMain1996.class})
public class Test {
    @Resource
    private PwNoteService pwNoteService;

    @org.junit.Test
    public void getMybatis()
    {
        System.out.println("hello");
        PwNote pwNote = pwNoteService.queryById(2);
        System.out.println(pwNote);
    }
}

这样就能输出service的结果了,当然前提是你的配置和类都没有问题。

常见注意事项

一般测试类的包都在单独的src->test->java下面,
而不是src->main->java下面,所以一般会指定junit的范围为test

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

这样和实际的代码分离,不然到时候你写的测试类,别人还以为是业务代码,也不敢乱删,但是你一个人开发,想着方便一点就在普通的包下,你可以指定范围为compile,这样就可以用了

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>compile</scope>
        </dependency>

小技巧

  1. 一般范围限定在test
  2. 如果test类中使用了插入删除等操作测试,打包的时候注意跳过测试,就是maven上面图标有个闪电的标志,点上,不然会运行一次测试类,导致出现数据库修改。
  3. 查看编译后的源码使用maven的clean就会删除target文件夹,compile就会重新编译生成,不用手动删除
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值