【问题标题】:How to mock dynamodbmapper scan如何模拟 dynamodbmapper 扫描
【发布时间】:2017-05-01 17:58:04
【问题描述】:

我有以下要模拟的代码:

public void getOrders(Response response){
    logger.log("Getting all orders");

    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
            .withProjectionExpression("OrderId");

    PaginatedScanList<Orders> orders = dynamoDBMapper.scan(Orders.class, scanExpression);

    response.setData(orders..stream()
            .collect(Collectors.toList()));
}

我试图模拟的方式是:

Mockito.when(mockDynamoDBMapper.scan(Orders.class, 
             Mockito.any())).thenReturn(mockPaginatedList);

我得到以下异常:

如果匹配器与原始值组合,则可能会发生此异常: //不正确: someMethod(anyObject(), "原始字符串");使用匹配器时,所有参数都必须由匹配器提供。例如: //正确的: someMethod(anyObject(), eq("匹配器的字符串")); 有关更多信息,请参阅 Matchers 类的 javadoc。

我应该如何用任何DynamoDBScanExpression 对象模拟dbmapper.scan 方法?

【问题讨论】:

    标签: java unit-testing testing mockito amazon-dynamodb


    【解决方案1】:

    该错误对您的问题有明确的答案。你想要的是:

    Mockito.when(mockDynamoDBMapper.scan(eq(Orders.class), 
                 Mockito.any())).thenReturn(mockPaginatedList);
    

    必须为匹配器提供匹配器 - eq(Orders.class),而不是原始值 - Orders.class

    【讨论】:

      【解决方案2】:

      一般来说,我首先要模拟 PaginatedScanList,这是 mapper.scan () 给我们的响应类型,然后我将该响应模拟分配给它在扫描 () 时创建的映射器模拟被称为

          // here I define the values ​​that will be assigned to the filter
          Map <String, AttributeValue> expressionAttributeValues ​​= new HashMap <> ();
          expressionAttributeValues.put (": attributeValue", new AttributeValue (). withS ("value"));
          // the definition of the epxpression for the scan
          DynamoDBScanExpression scanExpression = new DynamoDBScanExpression ();
          scanExpression.setLimit (1); // amount of data to return
          scanExpression.setFilterExpression (("email =: attributeValue")); // the attribute to filter by
          scanExpression.setProjectionExpression ("id"); // the data to return from the row or json
          scanExpression.setExpressionAttributeValues ​​(expressionAttributeValues); // place the value by which to filter
      
          DynamoDBMapper mapper = mock (DynamoDBMapper.class); // The mock was created for the mapper, which is the one with different methods such as query, scan, etc.
          PaginatedScanList scanResultPage = mock (PaginatedScanList.class); // definition of the mock for the scan result
      
          when (scanResultPage.size ()). then (invocation -> 3); // what to return when the PaginatedScanList is called
      
          when (mapper.scan (Person.class, scanExpression)). then (invocation -> scanResultPage); // here returns our mocked PaginatedScanList for the scan function
      

      【讨论】:

      • 稍微解释一下就好了……
      • 而且由于格式错误,代码难以阅读。
      • 添加更多详细信息和代码,请检查并再次评分
      猜你喜欢
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      相关资源
      最近更新 更多