【问题标题】:Mock buildin class AWS Logs client builder模拟构建类 AWS Logs 客户端构建器
【发布时间】:2019-04-28 18:54:54
【问题描述】:

我正在尝试模拟和使用 AWS 构建类。但不断得到不同的错误。

虽然我正在测试一个完整的方法,但我可以模拟所有其他方法,但是当涉及到凭据形成时,使用 when then 也会引发异常。

 BasicAWSCredentials basic = new BasicAWSCredentials(clientToken, clientSecret);
  //Forming AWSLogs
 AWSLogs awsLogsClient = AWSLogsClientBuilder
            .standard()
            .withCredentials(new AWSStaticCredentialsProvider(basic))
            .withRegion(region)
            .build();

 DescribeLogStreamsRequest logStreamsRequest = new 
 DescribeLogStreamsRequest().withLogGroupName("SomeLogGroupName");

 //This is where I am getting error while mocking. But this same exectes properly while running with actual credentilas. But while mocking it fails       
 DescribeLogStreamsResult describeLogStreamsResult = awsLogsClient.describeLogStreams(logStreamsRequest);

执行 Junit mockito 测试时出现错误消息。

Caused by: com.amazonaws.services.logs.model.UnrecognizedClientException: The security token included in the request is invalid. (Service: AWSLogs; Status Code: 400; Error Code: UnrecognizedClientException; Request ID:

如果只为上述代码创建 Mockito 测试,那将会很有帮助。我对 Mockito 完全陌生

【问题讨论】:

    标签: java unit-testing junit mockito powermock


    【解决方案1】:

    由于您正在编写单元测试,因此您不想使用 awsLogsClient 进行真正的 http 调用,而是想为该客户端创建一个模拟,以便您可以控制返回的响应。通过这样做,您可以测试代码的成功和失败案例。这样做的另一个好处是,您的单元测试将在没有 Internet 连接的情况下执行得更快。

    我将从模拟界面开始: https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/logs/AWSLogs.html

    但是您需要一些机制来将此依赖项注入到您的生产代码中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-30
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多