Mockito的简单使用(二)

Mockito的简单使用可以参考上一篇Mockito的简单使用

一、Mock测试框架常用注解介绍

1、spy和mock生成的对象不受spring管理

2、spy调用真实方法时,其它bean是无法注入的,要使用注入,要使用SpyBean

3、SpyBean和MockBean生成的对象受spring管理,相当于自动替换对应类型bean的注入,比如@Autowired等注入。

二、Mock测试框架常用使用方式

2.1 Mock初始化

为了减少单测与spring框架的耦合,并且尽量不使用真实对象进行模拟(官方文档建议,链接见文章底部),建议使用@InjectMocks创建实例,对于测试类中其他需要注入的依赖使用@Mock。在测试之前需要对Mock初始化,之后需要关闭Mock。如果有一些公共的静态类需要在多个测试用例中使用,推荐使用这种方式,代码如下。

private AutoCloseable closeable;

@Before
public void openMocks() {
  closeable = MockitoAnnotations.openMocks(this);
}

@After
public void releaseMocks() throws Exception {
  closeable.close();
}

如果没有公共的方法,也可以使用注解的方式直接初始化Mock

@RunWith(MockitoJUnitRunner.class)
public class MockTest {
    @Test
    public void test1() {
      
    }
}

2.2 简单流程单测

对于没有分支逻辑的功能,可以对结果断言,测试代码逻辑是否正确。并且需要注意,每个单测都需要进行断言,来验证代码逻辑的正确性。

public DemoTest{
    @Mock
    private Demo demoMock;
   
    @Test
    public void test1() {
        int i = 10;
        when(demoMock.Func(i)).thenReturn(false);
        boolean result = demoMock.Func(i);
        Assert.assertFalse(result);
    }
}

class Demo {
    public boolean Func(int i) {
        return i > 0;
    }
}

2.3 分支流程单测

当逻辑中有分支逻辑时,可以通过多个测试方法构造不同的对象,测试不同分支的逻辑正确与否

public DemoTest{
    @Mock
    private Demo demoMock;
   
    @Test
    public void test1() {
        int i = 10;
        when(demoMock.Func(i)).thenReturn(false);
        boolean result = demoMock.Func(i);
        Assert.assertFalse(result);
    }

    @Test
    public void test2() {
        int i = 0;
        when(demoMock.Func(i)).thenReturn(true);
        boolean result = demoMock.Func(i);
        Assert.assertTrue(result);
    }
}

class Demo {
    public boolean Func(int i) {
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }
}

2.4 验证方法被执行过的次数

// 验证方法被执行的次数
Mockito.verify(className,times(1)).doSomething();
Mockito.verify(className,times(2)).doSomething();
// 验证方法是否没被执行过
Mockito.verify(className,never()).doSomething();

注意:Mockito.verify()不可以验证被@InjectMocks修饰的mock对象

2.5 为调用的方法抛出异常

doThrow(new Exception()).when(className).doSomething();

2.6 静态方法的mock

try (MockedStatic<Lion> lionMock = mockStatic(Lion.class)) {
  lionMock.when(() -> Lion.getBoolean(anyString(), anyString(), anyBoolean())).thenReturn(true);
}

注意:对静态方法的打桩,应该使用try(){}的结构包裹起来,避免不同测试方法中的静态数据相互影响

也可以将Mock的静态方法抽成函数,传入功能接口函数,供测试类调用

public abstract class BaseTest {
  	private AutoCloseable closeable;
  
		public interface VoidFunc {
        void execute();
    }

    public static void getUserInfo(VoidFunc func){
      User user = new User();
      user.setId(1);

      try (MockedStatic<UserUtils> userUtilsMockedStatic = mockStatic(UserUtils.class)) {
        userUtilsMockedStatic.when(UserUtils::getUser).thenReturn(user);
        func.execute();
      }
    }
  
    @Before
    public void openMocks() {
        closeable = MockitoAnnotations.openMocks(this);
    }

    @After
    public void releaseMocks() throws Exception {
        closeable.close();
    }
}

public class ControllerTest extends BaseTest {
    @Test
    public void test() {
        BaseTest.getUserInfo(()->{
            ...
        });
    }
}

当一个静态方法依赖与另一个静态方法时,可以使用嵌套调用的结构

public abstract class BaseTest {
  	private AutoCloseable closeable;
  
		public interface VoidFunc {
        void execute();
    }
		
  	// 线程池(ExecutorService)内部依赖于限流器(OneLimiter),所以需要Mock线程池时,需要提前Mock限流器
    public static void getOneLimiter(VoidFunc func) {
        OneLimiter limiter = mock(DefaultOneLimiter.class);
        try (MockedStatic<Rhino> rhinoStatic = mockStatic(Rhino.class)) {
            rhinoStatic.when(Rhino::newOneLimiter).thenReturn(limiter);
        }

    }

    public static void getExecutorService(VoidFunc func) {
        ExecutorService mockedThreadPool = mock(ExecutorService.class);
        try (MockedStatic<ExecutorService> executorServiceMockedStatic = mockStatic(ExecutorService.class)) {
            executorServiceMockedStatic.when(() -> ExecutorServices.forThreadPoolExecutor(Mockito.anyString()))
                    .thenReturn(mockedThreadPool);
            func.execute();
        }
    }
  
    @Before
    public void openMocks() {
        closeable = MockitoAnnotations.openMocks(this);
    }

    @After
    public void releaseMocks() throws Exception {
        closeable.close();
    }
}

public class ControllerTest extends BaseTest {
    @Test
    public void test() {
        getOneLimiter(() -> getExecutorService(() -> {
            ...
        }));
    }
}

2.7 其他情况的Mock

对于void类型的方法,可以忽略掉方法的执行逻辑

doNothing().when(className).doSomething();

参考链接:

官方说明文档:https://github.com/hehonghui/mockito-doc-zh#12

SpringBoot - 单元测试利器Mockito入门_小小工匠的技术博客_51CTO博客

Springboot单元测试:SpyBean vs MockBean - 掘金

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值