spring boot 做controller层的单元测试

以前项目做单元测试那不叫单元测试,单元测试中的单元局限在类的方法中,很多数据不应该依赖第三方,应该自己mock数据,否则就应该叫集成测试了,就像如何写好单元测试:Mock脱离数据库+不使用@SpringBootTest
中说的差不多,但是也有差异,建议可以看一看

回归正题,这一篇博客主要讲的是在项目的controller层做单元测试,而且既然是单元测试,肯定像服务就需要mock数据

一、直接看代码,一个小demo


import com.example.demo.controller.TestController;
import com.example.demo.entity.User;
import com.example.demo.service.FirstService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author 孔超
 * @date 2021/2/28 21:51
 */
//@SpringBootTest  这个千万不要用,要不就要启动整个web项目
@RunWith(SpringJUnit4ClassRunner.class)
public class TestControllerTest {
    //需要mock的服务
    @Mock
    FirstService firstService;
    
    //上面mock的数据需要注入到哪里
    @InjectMocks
    TestController testController;

    @Test
    public void test() {
        //准备mock返回的数据
        User user = new User();
        user.setId(1L);
        user.setName("孔超");
        user.setAge("16");

        //mock服务或者类中的某个方法,当参数是什么时,返回值是什么
        Mockito.when(firstService.getUser(1L)).thenReturn(user);

        //执行单元测试逻辑
        User result = testController.getUser(1L);

        //断言
        Assert.assertEquals("孔超", result.getName());
    }
}

二、controller层代码


@Controller
public class TestController {
    @Resource
    FirstService firstService;

    @RequestMapping(value = "/getUser.do")
    public User getUser(Long id) {
        return firstService.getUser(id);
    }

  
}

三、需要的依赖

1、@RunWith(SpringJUnit4ClassRunner.class)

需要下面的依赖

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

2、mockito的依赖

spring-boot-starter-test的依赖已经集成了mockito的依赖,可以去里面看看

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

这样一个完整的controller层单元测试就完成了,虽然依然依赖于spring,但是不需要初始化整个web项目,执行速度提升了,数据污染减少了,不像服务可以加事务注解,因为是微服务的,在这加事务注解影响不到服务层。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值