java - Junit 测试模拟服务并过滤结果

标签 java testing junit mockito amazon-dynamodb

我想测试以下功能(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/

相关文章:

java - 测试实现相同接口(interface)的类的最佳方法

java - 实例化类时出错 :class:null java. lang.reflect.InitationTargetException

java - 文件扫描程序无限期挂起

Java列表实例在复制后保留其指针

c# - 如何使用 NServiceBus 执行集成测试?

ruby-on-rails - 无法访问类 nil Rails 4 的对象

java - 在 Eclipse 中运行 Junit 测试,不断得到 "NoClassDefFoundError"

java - JVM - WeakReferences 是否在次要 GC 中收集?

java - 无法通过子类实例从自己的类访问私有(private)变量

testing - Java 8 Lambda 的单元测试