我想测试以下功能(Junit 测试)。我正在使用 Mockito 模拟 Dynamodao 服务(它从 dynamodb 获取项目)。我正在根据所有者姓名过滤项目。
owner = this.getUser(httpRequest);
List<MapData> result = this.dynamoDao.getAllRecords(TABLE_NAME, Regions.US_WEST_2);
List<MapData> result1 = result.stream().filter(x -> owner.equals(x.getOwner()))
.collect(Collectors.toList());
这里的 MapData 是一个拥有 Owner 作为 dynamodbattribute 的类。我阅读了有关 Mockito 的信息,并意识到我需要它来模拟服务。
@Mock
private DynamoDao dynamoDao;
如何测试这个简单的功能?我真的可以使用一些帮助来了解如何进行。我怎么能在这里使用“何时”?我尝试在线查看示例代码,但不太了解。
最佳答案
因此,被测类有一个方法,其中包含您在上面显示的几行代码。此外,我假设 DynamoDao
的实例可能通过构造函数注入(inject)到此类中。
鉴于这些假设,您的测试用例可能看起来像这样:
@RunWith(MockitoJunitRunner.class)
public class MyTest {
@Mock
private DynamoDao dynamoDao;
@Test
public void testSomething() {
// create an instance of MapData which matches the behaviour expected of this test
List<MapData> expectedResult = ...;
when(dynamoDao.getAllRecords(re(TABLE_NAME), eq(Regions.US_WEST_2))).thenReturn(expectedResult);
// now invoke your method i.e. the one from which the extract in your question is taken
// now add assertions which match how you expect your method to behave when dynamoDao returns the expectedResult you created above
}
}
所以,简单地说:
- 注释类以确保模拟已初始化
- 将模拟注入(inject)被测类
- 告诉 mock 返回一些数据,让您可以指导 mock 的行为
- 调用被测方法
- 断言被测方法行为正确
关于java - Junit 测试模拟服务并过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292088/