2.1单元测试入门

步骤

1.模拟数据

@SpringBootTest
@RunWith(SpringRunner.class)
public class DeviceModelLableServiceTest {

    @Mock
    private DeviceModelLabelRespository repository;

    @Mock
    private DeviceInstanceRepository deviceInstanceRepository;

    @InjectMocks
    private DeviceModelLabelServiceImpl service;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void insertDeviceModelLable() {
     //模拟dao
     DeviceModelLabel deviceModelLable = new DeviceModelLabel();
     when(repository.findByDeviceModelId("deviceModelId")).thenReturn(lables);
     ...
    }
}

2.运行待测试代码

    @Test
    public void insertDeviceModelLable() {
     ...
     //单元测试
     List<DeviceModelLabel> results = service.listDeviceModelLabel("deviceModelId");
     ...
    }

3.断言

    @Test
    public void insertDeviceModelLable() {
     ...
     //断言
     Assert.assertEquals(deviceModelLable, results.get(0));
     Assert.assertEquals(deviceModelLable1, results.get(1));
     Mockito.verify(data, Mockito.times(1)).add("a");
    }

常用mockito方法

方法

说明

when(methodCall).thenReturn(object)

有返回值的方法返回对象

when(methodCall).thenThrow(throwables)

有返回值的方法抛出异常

doNothing().when(mock)

无返回值的方法什么都不做

doThrow(throwable).when(mock)

无返回值的方法抛出异常

常用断言

方法

说明

assertArrayEquals(expecteds, actuals)

查看两个数组是否相等。

assertEquals(expected, actual)

查看两个对象是否相等。类似于字符串比较使用的equals()方法

assertNotEquals(first, second)

查看两个对象是否不相等。

assertNull(object)

查看对象是否为空。

assertNotNull(object)

查看对象是否不为空。

assertSame(expected, actual)

查看两个对象的引用是否相等。类似于使用“==”比较两个对象

assertNotSame(unexpected, actual)

查看两个对象的引用是否不相等。类似于使用“!=”比较两个对象

assertTrue(condition)

查看运行结果是否为true。

assertFalse(condition)

查看运行结果是否为false。

assertThat(actual, matcher)

查看实际值是否满足指定的条件

fail()

让测试失败

参考文档

Mockito 精萃

Last updated

Was this helpful?