pav*_*163 5 java amazon-web-services aws-lambda
我正在为从S3触发,获取一些文件数据并将其放入另一个S3存储桶的AWS Lambda实现Java 8程序包。
这是我目前的情况Handler
:
public class Handler implements RequestHandler<S3Event, Void> {
private static final String TARGET_BUCKET = "some-bucket";
private AmazonS3Client s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain());
private Runner runner = new Runner(s3Client, TARGET_BUCKET);
@Override
public Void handleRequest(S3Event s3Event, Context context) {
runner.run(s3Event, context);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我将业务逻辑移到了我的Runner
课堂上,以便可以正确地对其进行测试(遵循AWS Lambda最佳实践白皮书)。
但是,我正在努力查看如何通过伪造品S3Event
来测试我的run
功能。
我目前的测试是:
@Test
public void putsDataIntoS3() throws IOException {
runner.run(new ObjectMapper().readValue(loadJsonFromFile("s3-event.json"), S3Event.class), context);
assertTrue(true);
}
Run Code Online (Sandbox Code Playgroud)
在哪里loadJsonFromFile
获取带有我传递的文件名的资源,将其转换为输入流,然后转换为String
。
但是,这会导致错误:
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.amazonaws.services.lambda.runtime.events.S3Event]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何run
通过传递伪S3Event
JSON 正确测试我的功能?
这些是我正在使用的与aws相关的依赖项:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.455</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我可以这样使用该S3Event.parseJson
函数:我也已经看过该parseJson
函数,并且可以这样使用它:
@Test
public void putsFilteredDataIntoS3() throws IOException {
runner.run(new S3Event(S3Event.parseJson(loadJsonFromFile("s3-event.json")).getRecords()), context);
assertTrue(true);
}
Run Code Online (Sandbox Code Playgroud)
但是,这是否是最佳做法?
您可以使用Mockito库并尝试对此进行模拟S3Event
。
S3Event
从JSON 创建的另一个选项:
S3EventNotification notification = S3EventNotification.parseJson(loadJsonFromFile("s3-event.json"));
S3Event event = new S3Event(notification.getRecords());
Run Code Online (Sandbox Code Playgroud)
编辑:
第三个选项是将您更新aws-lambda-java-events
到version 2.2.4
,在其中他们为其添加了默认构造函数,S3Event
因此您可以像这样反序列化它:
objectMapper.readValue(loadJsonFromFile("s3-event.json"), S3Event.class)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
757 次 |
最近记录: |