Mockito2 探索

简介

核心元素

  • 将mock的底层引擎CGLIB 更改为 ByteBuddy

  • 为JAVA8做准备

  • Mockito的Junit runner 和 rule规则器 可以探测不用stubs

1
2
3
4
5
// detect unused stubs
@RunWith(MockitoJUnitRunner.class)

// don't detect, old behaviour
@RunWith(MockitoJUnitRunner.Silent.class)

or with the rule

1
2
3
4
5
6
7
// detect unused stubs
@Rule
public MockitoRule mrule = MockitoJUnit.rule();

// don't warn user about misusage, old behaviour
@Rule
public MockitoRule mrule = MockitoJUnit.rule().silent();
  • 对于框架的整合者或高级用户,提供新的APIorg.mockito.listeners.MockitoListener来探测无用的sutbs

  • 新的校验控制器支持懒校验Lazy verification

1
2
@Rule
public VerificationCollector collector = MockitoJUnit.collector();

在一个测试方法中,所有的校验都会被执行并报告出来,即使校验报错

1
2
3
4
IMethods methods = mock(IMethods.class);
// Both methods are not called, but will be reported at once
verify(methods).simpleMethod();
verify(methods).byteReturningMethod();

默认的非懒校验的方式,会在simpleMethod停止校验,并不会报告未进行校验的方法byteReturningMethod

  • More Answers
  1. Introducing Answers.RETURNS_SELF, which should be useful to mock builders
  2. Java 8 friendly answers AdditionalAnswers.answer(arg1 -> arg1.toString())
  • 改善BDDMockito的API
1
2
3
BDDMockito.then(mock).should(inOrder).doSomething();
BDDMockito.then(mock).shouldHaveZeroInteractions();
BDDMockito.then(person).shouldHaveNoMoreInteractions();

地心历险

揭示底层的原理


实战

实际使用中常用的东西


参考资料

What’s new in Mockito2


Mockito2 探索
https://oabern.github.io/posts/201612133008866774/
作者
OABern
发布于
2016年12月13日
许可协议