gpt4 book ai didi

java - 如何在 Spring Boot 应用程序中模拟外部依赖关系?

转载 作者:行者123 更新时间:2023-12-02 03:39:10 25 4
gpt4 key购买 nike

我需要测试一个 SpringBoot 应用程序,我在其中针对端点运行测试(目前在本地)。

有一个从服务到外部服务 ( s3 ) 的调用,我只需要模拟它,这样我们就不会实时调用 s3 。根据我们的测试。

我使用 Mockito 进行模拟。

调用堆栈:

Controller -service

-external service.

根据我的测试,我刚刚到达终点网址 ( localhost:8080/actions/domyjob )

这是我的 Controller :

@RestController
@RequestMapping("/myjob")
public class MyController{

@Autowired
private MyService myService;

@RequestMapping(path = "/doJobInMyService", method = POST)
public void doJobInMyService(){
myService.doMyJob()
}

}

这是我的服务:

@Service
public class MyService {

@Autowired
private s3Client AmazonS3Client;

doMyJob() {
s3Client.putObject(new PutObjectRequest());
}
}

如果你看到了,如果我想测试整个流程,可以通过调用 localhost:8080/myjob/doJobInMyService只是 mock s3Client.putObject(new PutObjectRequest()) ,让外部调用s3还没有完成。

尝试过这个,但我仍然没有运气:

@ActiveProfiles("MyTestConfig")
@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest extends BaseTest {
@Autowired
private AmazonS3Client amazonS3Client;

@Test
public void testMyResponse() {
try {
Mockito.when(amazonS3Client.putObject(anyObject())).thenReturn(new PutObjectResult());
assertNotNull(getMyClient().doMyJob());
} catch(Exception e) {

}
}
}

@Profile("MyTestConfig")
@Configuration
public class MyTestConfiguration {

@Bean
@Primary
public AmazonS3Client amazonS3Client() {
return Mockito.mock(AmazonS3Client.class);
}

最佳答案

自 Spring Boot 1.4.x 起,Mockito 通过注释 @MockBean 原生支持 Spring beans 模拟。请参阅this section of Spring Boot docs了解更多信息。

关于java - 如何在 Spring Boot 应用程序中模拟外部依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37049150/

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