如何为一种方法添加多个合约?使用 Spring Cloud Contract Verifier + groovy 进行合约测试

问题描述 投票:0回答:1
我试图为一种方法制作两种情况:当响应包含元素列表和空列表时。对于这两种情况,我都有 BaseTestClass,但响应主体的生成应该根据合同的不同而有所不同。是否可以?如果是,该怎么做? BaseTestClass 如何知道要调用哪个模拟?

@ActiveProfiles("test") @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @DirtiesContext @AutoConfigureMessageVerifier public class BaseTestClass { @Autowired private MyController myController; @MockBean private MyService myService; @BeforeEach public void SetUp() { StandaloneMockMvcBuilder standaloneMockMvcBuilder = MockMvcBuilders.standaloneSetup(channelController); standaloneMockMvcBuilder.setControllerAdvice(new MyExceptionHandler()); standaloneMockMvcBuilder.setMessageConverters(new MappingJackson2HttpMessageConverter()); RestAssuredMockMvc.standaloneSetup(standaloneMockMvcBuilder); //mockGetAllChannels(); // when it was the only contract, mock was called here } @Test void testChannelsOk() { mockGetAllChannels(createChannelList()); } @Test void testEmptyList() { mockGetAllChannels(Collections.emptyList()); } private void mockGetAllChannels(List<ChannelResponse.Channel> channelList) { doReturn(ChannelResponse.builder() .channels(channelList) .build()) .when(myService) .getAllChannels(); } private List<ChannelResponse.Channel> createChannelList() { //generation logic }
Groovy 文件:

[ Contract.make { name("two channels") request { method 'GET' url('/channels') headers { header('Content-Type', 'application/json;charset=UTF-8') } } response { status 200 body( channels: [[ id : anyNonBlankString(), name : anyNonBlankString(), ] ] ) } }, Contract.make { name("empty list") request { method 'GET' url('/channels') headers { header('Content-Type', 'application/json;charset=UTF-8') } } response { status 200 body( channels: [] ) } } ]
我也尝试将其放在单独的文件中,我不确定哪种方法更好。
我看到过这种做多个合约的例子:

@Test void testEmptyList()
但是不起作用。

java spring testing spring-cloud spring-cloud-contract
1个回答
0
投票
@stakeika - 我有同样的问题,但角度不同。 我可以在一个 groovy 测试文件中包含多个合约,但是在编译过程中,它会获取最后一个 contact.make() 方法内容并为其生成源代码。当我执行合约测试时,它总是执行 groovy 测试文件中存在的最后一个合约方法。

请告诉我您是否仍在同一条船上或能够继续前进吗?

© www.soinside.com 2019 - 2024. All rights reserved.