java单元测试,最好用的mock框架是什么?

一、背景

接着上一篇文章:单元测试入门,本篇文章作为单元测试的进阶篇,主要介绍如何对Springboot Service层代码做单元测试,以及单元测试中涉及外调服务时,如何通过Mock完成测试。

二、Springboot Service层代码单元测试

现在项目都流行前后端代码分离,后端使用springboot框架,在service层编写接口代码实现逻辑。假设现在前端不是你写的,你要对你自己写的后端springboot service层提供的接口方法做单元测试,以确保你写的代码是能正常工作的。

Service层代码单元测试:一个简单的service调mapper查询数据库replay_bug表数据量的接口功能

ReplayBugServicelmpl类代码:

@Service
public class ReplayBugServiceImpl implements ReplayBugService {

    @Autowired
    ReplayBugMapper replayBugMapper;

    @Override
    public int queryBugTotalCount() {
        return replayBugMapper.queryBugTotalCount();
    }
}

replayBugMapper.queryBugTotalCount代码:

@Select("select count(1) from replay_bug")
int queryBugTotalCount();

单元测试ReplayBugServiceImplTest类代码:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class ReplayBugServiceImplTest{
    @Autowired
    ReplayBugServiceImpl replayBugService;

    @Test
    public void queryBugTotalCount() {
        int bugCount=replayBugService.queryBugTotalCount();
        System.out.println("结果是:"+bugCount);
    }
}

代码很简单,调用这个接口服务,打印输出,测试是否能正确查出数据。其中关键的两个注解解释:

@RunWith(SpringRunner.class)注解:是一个测试启动器,可以加载SpringBoot测试注解。
让测试在Spring容器环境下执行。如测试类中无此注解,将导致service、dao等自动注入失败。

@SpringBootTest注解:目的是加载ApplicationContext,启动spring容器。

测试结果如下:

更进一步,测试带入参的service接口:新增接口单元测试

import com.test.service.BestTest;
import com.test.domain.UrlWhiteListVO;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ReplayUrlWhiteListServiceImplTest{
    @Autowired
    ReplayUrlWhiteListServiceImpl replayUrlWh
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值