如何在JUnit测试中Mock SimpleMessageListenerContainer以规避AWS密钥?
问题
生产环境中,通过以下代码构建AmazonSQSAsync连接并传入有效密钥,运行正常:
public AmazonSQSAsync getAmazonSQSAsync() { return AmazonSQSAsyncClientBuilder.standard().withRegion(Regions.RegionName) .withCredentials(new AWSStaticCredentialsProvider(new BasicSessionCredentials(accessKey, secretKey, sessionToken))) .build(); }
但在CI/CD服务器上无密钥运行JUnit测试时,持续抛出如下异常:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'simpleMessageListenerContainer' defined in class path resource [org/springframework/cloud/aws/messaging/config/annotation/SqsConfiguration.class]: The security token included in the request is invalid. (Service: AmazonSQS; Status Code: 403; Error Code: InvalidClientTokenId; Request ID: 2c866447-fc44-558a-9e93; Proxy: null)
尝试Mock SimpleMessageListenerContainerFactory未生效,希望Mock相关Bean以实现无真实密钥即可注入。
解决方法
1. Mock核心的AmazonSQSAsync Bean
直接Mock最底层的AmazonSQSAsync接口,替换掉真实的客户端实现,这是Spring Cloud AWS SQS组件的核心依赖:
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import com.amazonaws.services.sqs.AmazonSQSAsync; @SpringBootTest public class SqsModuleTest { @MockBean private AmazonSQSAsync amazonSQSAsync; // 你的测试逻辑 }
@MockBean会自动替换Spring容器中原有的AmazonSQSAsync Bean,所有依赖它的组件(包括SimpleMessageListenerContainer)都会使用Mock实例,不会发起真实AWS请求,自然无需密钥。
2. 禁用SQS自动配置(Spring Boot项目适用)
如果测试不需要启动SQS监听容器,直接禁用Spring Cloud AWS的SQS自动配置类:
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration; @SpringBootTest @EnableAutoConfiguration(exclude = SqsConfiguration.class) public class SqsModuleTest { // 你的测试逻辑 }
这样Spring不会创建simpleMessageListenerContainer等相关Bean,从根源避免密钥校验问题。
3. 自定义测试配置类替换Bean
若需要更精细的控制,编写测试专用配置类手动提供Mock的AmazonSQSAsync:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.amazonaws.services.sqs.AmazonSQSAsync; import static org.mockito.Mockito.mock; @Configuration public class TestSqsConfig { @Primary @Bean public AmazonSQSAsync amazonSQSAsync() { return mock(AmazonSQSAsync.class); } }
在测试类中引入该配置:
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; @SpringBootTest @Import(TestSqsConfig.class) public class SqsModuleTest { // 你的测试逻辑 }
@Primary确保Mock Bean被优先注入,覆盖生产环境的配置。
关键说明
之前Mock SimpleMessageListenerContainerFactory无效,是因为SimpleMessageListenerContainer最终仍依赖AmazonSQSAsync客户端,仅Mock工厂无法阻止真实客户端的创建和密钥校验。若需模拟消息收发逻辑,可通过Mockito的when()方法给Mock的AmazonSQSAsync设置预期行为,比如模拟发送成功或返回指定消息。
内容的提问来源于stack exchange,提问作者Saurabh Tiwari

