gpt4 book ai didi

java - 如何在单元测试中模拟 AmazonSQS 而不调用 SQS?

转载 作者:行者123 更新时间:2023-12-03 23:00:43 33 4
gpt4 key购买 nike

我的 Java 中有以下方法类(class):

public class AwsHelper {

private AmazonSQS sqs;

private void sendMessageToQueue(String message){

sqs = AmazonSQSClientBuilder.defaultClient();

SendMessageRequest sendMessageRequest = new SendMessageRequest();
sendMessageRequest.setQueueUrl("");
sendMessageRequest.setMessageBody(message);
sendMessageRequest.setMessageGroupId("");

sqs.sendMessage(sendMessageRequest);
}
我希望能够模拟 sqs.sendMessage(sendMessageRequest); 的行为这样我的单元测试就不会向队列发送消息。
我在我的测试课中尝试这样做,但是 sqs当我的测试执行时,实际上会向队列发送一条消息。假设这是由 AmazonSQSClientBuilder.defaultClient() 分配的.
我该如何解决这个问题?
public class AwsSQSReferralsUtilTest {

@Spy
@InjectMocks
private AwsHelper awsHelper;

@Mock
AmazonSQS sqs;

@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
}

@AfterMethod
public void afterEachMethod() {
Mockito.reset(awsHelper);
}

@Test
public void shouldSendMessage() {

Mockito.when((sqs.sendMessage(any(SendMessageRequest.class)))).thenReturn(new SendMessageResult());

awsHelper.sendMessageToQueue("");
}
}

最佳答案

我建议使用文章中的方法:https://github.com/mockito/mockito/wiki/Mocking-Object-Creation
您需要稍微更改一个类,以以下方式应用文章中的模拟方法:
AwsHelper

public class AwsHelper {

private AmazonSQS sqs;

public void sendMessageToQueue(String message) {
sqs = defaultClient();

SendMessageRequest sendMessageRequest = new SendMessageRequest();
sendMessageRequest.setQueueUrl("");
sendMessageRequest.setMessageBody(message);
sendMessageRequest.setMessageGroupId("");

sqs.sendMessage(sendMessageRequest);
}

protected AmazonSQS defaultClient() {
return AmazonSQSClientBuilder.defaultClient();
}
}

AwsSQSReferralsUtilTest
public class AwsSQSReferralsUtilTest {

@Spy
private AwsHelper awsHelper;

@Mock
private AmazonSQS sqs;

@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
}

@AfterMethod
public void afterEachMethod() {
Mockito.reset(awsHelper);
}

@Test
public void shouldSendMessage() {
//mocking object creation
doReturn(sqs).when(awsHelper).defaultClient();

when(sqs.sendMessage(any(SendMessageRequest.class))).thenReturn(new SendMessageRequest());
awsHelper.sendMessageToQueue("");
}

}

关于java - 如何在单元测试中模拟 AmazonSQS 而不调用 SQS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65956878/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com