首页 > 其他分享 >进大厂必须要会的单元测试

进大厂必须要会的单元测试

时间:2022-11-22 13:56:20浏览次数:35  
标签:HelloService helloDao Mockito 单元测试 大厂 要会 hello mock helloService

本文将按照如下顺序给大家简单讲讲单元测试应该怎么写

什么是单元测试

单元测试又称模块测试,是针对软件设计的最小单位(模块)就行正确性的校验的测试,检查每个程序模块是否实现了规定的功能,保证其正常工作。

测试的重点:系统模块、方法的逻辑正确性

和集成测试不同,单元测试应该具备如下特点:

  1. 尽可能简短不重复
  2. 执行速度快,因为单元测试几乎可以一直运行,所以对于一些数据库、文件操作等一定要加快速度,可以采用mock的方式
  3. 具有100%的确定性,不能某几次可以执行成功,某几次执行失败

我们在企业开发中,很多大公司都是要求单测到达一定的比率才能提交代码,单测能够保证我们写的逻辑代码符合我们的预期,并且在后续的维护中都能通过单测来验证我们的修改有没有把原有的代码逻辑改错。

虽然会花费我们额外10%的时间去做单测,但是收益率还是值得的,作为一个开发,我认为我们本就该进行完整的自测后才移交给测试同学。

单元测试入门

先写一个简单的单测例子:测试一个求两个set集合交集的方法

  1. 引入依赖
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>4.3.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>
  1. 被测试方法
/**
     * 获取交集
     * @param set1
     * @param set2
     * @return
     */
    public Set<Integer> getIntersection(Set<Integer> set1,Set<Integer> set2){
        set1.retainAll(set2);
        return set2;
    }
  1. 生成测试方法

我们可以通过IDEA的自动生成功能来生成测试方法

它会在test目录下的同包名下生成一个测试类

  1. 我们编写测试逻辑
class HelloServiceTest {

    @Test
    void getIntersection() {
    //生成mock类
        HelloService helloService = Mockito.mock(HelloService.class);
        //调用mock类的getIntersection方法时调用真实方法
        Mockito.when(helloService.getIntersection(Mockito.anySet(),Mockito.anySet())).thenCallRealMethod();

        Set<Integer> set1=new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);


        Set<Integer> set2=new HashSet<>();
        set2.add(5);
        set2.add(4);
        set2.add(3);

        Set<Integer> intersection = helloService.getIntersection(set1, set2);
        Set<Integer> set3=new HashSet<>();
        set3.add(3);
        //断言,判断方法结果是否和我们预想的一致
        Assertions.assertEquals(intersection,set3);
    }
}
  1. 运行

运行结果:

运行完后发现断言异常,这样就能检查出我们之前写的代码不对,去检查了下,发现了问题,改正代码后重试。

 public Set<Integer> getIntersection(Set<Integer> set1,Set<Integer> set2){
        set1.retainAll(set2);
        return set1;
    }

常用方法

构建测试对象

  1. mock方法
  • 方法1
HelloService helloService = Mockito.mock(HelloService.class);
  • 方法2:
    使用注解
@Mock
private HelloService helloService;


@Test
void getIntersection() {
    //使用@Mock,需要加下面这行代码
    MockitoAnnotations.openMocks(this);
    Mockito.when(helloService.getIntersection(Mockito.anySet(),Mockito.anySet())).thenCallRealMethod();
    ...
    }

mock出来的对象,要指定方法的返回,否则只是返回默认值,不会执行真正的方法的实现。

  1. 直接使用new 方法构建对象
HelloService helloService = new HelloService();
  1. 使用@Spy注解
@Spy
private HelloService helloService;

使用@Spy注解的对象,在执行的时候会调用真实的方法。

上面都是简单的一级对象的构建,如果被测试的对象里面还要对象依赖怎么办呢?

构建依赖的测试对象

如这个方法:

@Setter
public class HelloService {


    private HelloDao helloDao;

    public String hello(){
        return helloDao.hello()+" xiaowang";
    }
    
}
  1. mock + set
HelloService helloService=new HelloService();
HelloDao helloDao = Mockito.mock(HelloDao.class);
helloService.setHelloDao(helloDao);
  1. @InjectMocks

使用@InjectMocks可以将mock出的依赖对象注入到它标注的测试对象中

    @InjectMocks
    private HelloService helloService;

    @Mock
    private HelloDao helloDao;

上面的例子中,将helloDao注入到了helloService中

构建静态对象

需要修改依赖

<!--        <dependency>-->
<!--            <groupId>org.mockito</groupId>-->
<!--            <artifactId>mockito-core</artifactId>-->
<!--            <version>4.3.1</version>-->
<!--            <scope>test</scope>-->
<!--        </dependency>-->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-inline</artifactId>
            <version>4.3.1</version>
            <scope>test</scope>
        </dependency>
MockedStatic<JsonUtils> tMockedStatic = Mockito.mockStatic(JsonUtils.class);

因为静态方法mock了之后,在整个线程中都是生效的,如果需要隔离的话,可以使用try-with-resources来写。

区别如下:

行为规定(打桩)

接下来我们学习方法的行为规定,因为mock出来的对象默认是不执行真实方法的,需要我们指定。

  1. doReturn
Mockito.doReturn("hello").when(helloDao).hello();
  1. thenReturn
Mockito.when(helloDao.hello()).thenReturn("hello");
  1. thenAnswer

这种方式可以灵活的返回,比如根据参数的不同返回不同的值

 Mockito.when(helloDao.hello(Mockito.anyString())).thenAnswer( invocation->{
            String param = invocation.getArgument(0);
            if(param.equals("w")){
                return "wang";
            }else {
                return "li";
            }
        });
  1. mock异常

有时候需要测试方法异常的时候对整个方法体的影响

Mockito.when(helloDao.hello(Mockito.anyString())).thenThrow(NullPointerException.class);

断言

我们执行完测试方法后,就需要对结果进行验证比对,来证明我们的方法的正确性。

  1. Assertions.assertEquals
Assertions.assertEquals(hello,"hello xiaowang");
  1. Assertions.assertTrue
Assertions.assertTrue(hello.equals("hello xiaowang"));
  1. Assertions.assertThrows

异常断言,判断是否是预期的异常

Assertions.assertThrows(NullPointerException.class,()->{
            helloDao.hello();
        });
  1. 使用Verify断言执行次数
Mockito.verify(helloDao,Mockito.times(1)).hello();

番外

另外还有两个注解,@BeforeEach和@AfterEach,顾名思义,一个是在test方法执行前执行,一个是在test方法执行后执行。

@BeforeEach
public void before(){
   System.out.println("before");
}

@AfterEach
public void after(){
   System.out.println("after");
}

另外推荐两款比较好用的单测生成插件 TestMe 和Diffblue

标签:HelloService,helloDao,Mockito,单元测试,大厂,要会,hello,mock,helloService
From: https://www.cnblogs.com/javammc/p/16914892.html

相关文章

  • 单元测试中常见错误
    单元测试中常见错误单元的常见错误一般出现在5个方面:代码的稳定、易读、规范、易维护、专业。因此,单元测试的关注的重点有5点:单元接口、局部数据结构、边界条件......
  • 单元测试:会变化的定义
    有一种东西,如果它太小,需要付出的努力就太大;如果它太大,就很难测试。没错!它是单元。但是什么才是一个好的单元定义呢?为什么它如此重要? 单元的定义对测试过程有很大的......
  • Junit单元测试
    单元测试单元测试叫做模块测试,属于白盒测试,就是开发者编写的一小段代码,用于检测某个功能是否正确。白盒测试是懂代码的开发做的,需要对项目代码的进行编写测试代码。黑......
  • 单元测试
    MockitoMockito1.为什么要使用mock2.Mockito中常用方法2.1Mock方法2.2对Mock出来的对象进行行为验证和结果断言2.3给Mock对象打桩2.4Mock静态方法3.Mocki......
  • 单元测试2
    packagecom.echo.mockito.service.Impl;importcom.echo.mockito.dao.SalesDao;importcom.echo.mockito.dao.UserDao;importcom.echo.mockito.entity.User;importcom.e......
  • 开传奇需要哪些条件要会什么技术开服需要多少钱
    开传奇需要哪些东西一次给你说清楚对于这个问题,近期问的人比较多。这也是热爱传奇这个游戏的朋友会问到的一个问题,因为喜欢玩这个游戏,也想要自己去开一个经营一个不管是电......
  • 使用Mockito与Squaretest进行单元测试.
    项目开发过程中,不少公司都要求写单元测试的代码,可以提高代码的质量,并且可以减少出现BUG的概率。对于中小型公司来说,对单元测试不做硬性要求,不写最好。因为还是需要一......
  • 互联网大厂的后端技术栈
    最近公司招聘海外后端研发,所以整理一份技术栈的资料给他们,但是想来这份整理也适用于所有后端研发,所以去掉了敏感内容,把它呈现于此,本文重在概述,毕竟篇幅有限,欢迎【关注......
  • 单元测试 request_mock模拟网络调用
    importunittestfromunittestimportmockfromrequests.exceptionsimportConnectionErrorimportrequests_mockimportrequestsclassMyBugzilla:def__......
  • 测试面试 | 一道大厂算法面试真题,你能答上来吗?(附答案)
    时光飞快,眨眼又到一年年底!年底其实是跳槽换坑的绝佳时机,毕竟可以「年前面试,年后入职」,而且面试越早,好坑位较多,可选择的余地也较大。建议有换工作意向的测试同学可以多发发简......