gpt4 book ai didi

java - Spring引导2.2.0测试: Configuration error: found multiple declarations of @BootstrapWith

转载 作者:行者123 更新时间:2023-12-01 17:22:00 24 4
gpt4 key购买 nike

@RunWith(SpringRunner.class)
@SpringBootTest(classes=MyApplication.class)
@TestPropertySource(locations = "classpath:test-application.properties")
@WebAppConfiguration
@RestClientTest(Controller.class)
public class MyIntegrationTest {

}

当我运行这个时,我收到以下错误java.lang.IllegalStateException:配置错误:发现测试类有多个@BootstrapWith声明

最佳答案

根本原因是您同时使用了@SpringBootTest@RestClientTest
因为它会导致 @BootstrapWith 注解发生冲突。您可以看到下面的图片。

enter image description here

Tip: If you are using JUnit 4, don’t forget to also add@RunWith(SpringRunner.class) to your test, otherwise the annotationswill be ignored. If you are using JUnit 5, there’s no need to add theequivalent @ExtendWith(SpringExtension.class) as @SpringBootTest andthe other @…​Test annotations are already annotated with it.
Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing

如果您的测试用例很简单,您可以引用使用@RestClientTest的示例here .

就我而言,我定义了一些与测试服务相关的复杂配置(例如:jpaAuditingHandler、jpaMappingContext,...)。这就是我使用 @SpringBootTest 进行自动配置的原因。

这是我的代码示例:

@SpringBootTest
class MyTest {

@Autowired
private MyProperties myProperties;

@Autowired
private MyService myService;

private MockRestServiceServer server;

@Autowired
@Qualifier("restTemplateBean1")
private RestTemplate restTemplate;

@BeforeEach
void setUp() {
server = MockRestServiceServer.createServer(restTemplate);
}

@Test
void testCallRestServiceSuccess() throws Exception {
this.server.expect(requestTo(myProperties.getUrl())).andRespond(withStatus(HttpStatus.OK));

boolean result = myService.callRestService();
assertThat(result).isTrue();
}
}

其他一些引用:

关于java - Spring引导2.2.0测试: Configuration error: found multiple declarations of @BootstrapWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61276620/

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