Mockito分享

2017-03-08 11:01:42

mockito

  • 引入pom依赖,最新版本2.7.14
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.7.14</version>
</dependency>
  • Annotations

@Mock注解生成mock类,@Spy注解可调用模拟和真实对象方法,@InjectMocks注解会自动将标记@Mock、@Spy等注解的属性值注入到被测试类中,注意上面注解生效需用@RunWith(MockitoJUnitRunner.class)或者调用MockitoAnnotations.initMocks(this)方法初始化

@Spy
private AddressService addressService;
@Mock
private HostService hostService;
@InjectMocks
private CustomerService customerService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
  • Stubbing

语法形式:when-method-call-then-return


Customer customer = new Customer("204", "John Do", "221B Bakerstreet");
when(addressService.getPLZForCustomer(customer)).thenReturn(47891);
  • verify

verify是对历史记录作一种回溯校验的处理,关注方法是否调用及调用次数

verify(addressService).getAddressForCustomer(customer);
verify(addressService,times(3)).getAddressForCustomer(customer);

powerMock

powermock是对Mockito与EasyMock的扩展,能mock构造方法、私有方法和静态方法,但需要多引用一个扩展jar包,其中对Mockito扩展和Mockito语法很相似,二者任选其中即可

断言

推荐一个比较好用的断言库,AssertJ

  • 引入pom依赖
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<!-- use 2.6.0 for Java 7 projects -->
<version>3.6.2</version>
<scope>test</scope>
</dependency>
  • 静态导入assertj
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat; // main one
  • assertj用法
// basic assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron);
// chaining string specific assertions
assertThat(frodo.getName()).startsWith("Fro")
.endsWith("do")
.isEqualToIgnoringCase("frodo");
// collection specific assertions (there are plenty more)
// in the examples below fellowshipOfTheRing is a List<TolkienCharacter>
assertThat(fellowshipOfTheRing).hasSize(9)
.contains(frodo, sam)
.doesNotContain(sauron);