Я немного борюсь с проволокой. У меня есть 2 HTTP-звонка, которые нужно сделать. Они находятся на разных портах. Я создал 2 правила в тесте на разных портах. 1 настроенный URL работает нормально (я получил ожидаемый ответ в моем коде). Другой никогда не находит совпадения, когда он попадает в причал. Я не совсем уверен, что я делаю неправильно.
Я вижу эту ошибку в журналах:
service.document.SaveFileTest Time elapsed: 8.584 sec <<< FAILURE!
com.github.tomakehurst.wiremock.client.VerificationException: 10 requests were unmatched by any stub mapping. Requests are:
{
"url" : "/apiv1/registerChanges",
"absoluteUrl" : "http://localhost:11887/apiv1/registerChanges",
"method" : "POST",
"clientIp" : "127.0.0.1",
"headers" : {
"Authorization" : "bearer ken sent me",
"Accept" : "*/*",
"User-Agent" : "Java/1.8.0_242",
"Connection" : "keep-alive",
"Host" : "localhost:11887",
"Content-Length" : "939",
"Content-Type" : "application/json;charset=UTF-8"
},
"cookies" : { },
"browserProxyRequest" : false,
"loggedDate" : 1585850180844,
"bodyAsBase64" : "eyJpZCI6MCwiZW50aXR5IjoiZG9jdW1lbnQuZG9jdW1lbnQiLCJ0eXBlIjoiY3JlYXRlRG9jdW1lbnQiLCJlbnRpdHlSZWNvcmRJZCI6MTAsImF1dGhvckd1aWQiOiJlNDlmOWVjZi04Y2UyLTQ4NzMtODI3NC1iN2VmN2Q1MzlhNTIiLCJjaGFuZ2VEYXRlIjpudWxsLCJjb21tZW50cyI6bnVsbCwiYWRkaXRpb25hbEluZm8iOm51bGwsImNoYW5nZXMiOlt7ImlkIjowLCJmaWVsZCI6InN0YXR1cyIsImZyb21WYWx1ZSI6IiIsInRvVmFsdWUiOiJTdGF0dXModmVyc2lvbj0wLCBpZD0xLCBuYW1lPWFjdGl2ZSwgYXV0aG9yU2VydmljZT1BdXRob3JTZXJ2aWNlKHZlcnNpb249MCwgaWQ9MSwgbmFtZT1hY2NvdW50aW5nKSkifSx7ImlkIjowLCJmaWVsZCI6ImZ1bmN0aW9uIiwiZnJvbVZhbHVlIjoiIiwidG9WYWx1ZSI6IkZ1bmN0aW9uKHZlcnNpb249MCwgaWQ9MSwgbmFtZT1pbmZvLCBhdXRob3JTZXJ2aWNlPUF1dGhvclNlcnZpY2UodmVyc2lvbj0wLCBpZD0xLCBuYW1lPWFjY291bnRpbmcpKSJ9LHsiaWQiOjAsImZpZWxkIjoibmFtZSIsImZyb21WYWx1ZSI6IiIsInRvVmFsdWUiOiJyZXBvcnRzLnR4dCJ9LHsiaWQiOjAsImZpZWxkIjoiYXV0aG9yU2VydmljZSIsImZyb21WYWx1ZSI6IiIsInRvVmFsdWUiOiJBdXRob3JTZXJ2aWNlKHZlcnNpb249MCwgaWQ9MSwgbmFtZT1hY2NvdW50aW5nKSJ9LHsiaWQiOjAsImZpZWxkIjoib3duZXIiLCJmcm9tVmFsdWUiOiIiLCJ0b1ZhbHVlIjoiT3duZXIodmVyc2lvbj0wLCBpZD0xLCBndWlkPWNiMzY5MTBjLTUxMjMtNGNhNC1hYTk2LWQ1NjBiY2ZkMzhkZSkifSx7ImlkIjowLCJmaWVsZCI6ImlkIiwiZnJvbVZhbHVlIjoiMCIsInRvVmFsdWUiOiIxMCJ9LHsiaWQiOjAsImZpZWxkIjoidXVpZCIsImZyb21WYWx1ZSI6IiIsInRvVmFsdWUiOiI3OTI1ZDQ4MS1jNWRjLTQxOTMtYjdjYi1hNDQxOTEzZDkzZjgifV19",
"body" : "{\"id\":0,\"entity\":\"document.document\",\"type\":\"createDocument\",\"entityRecordId\":10,\"authorGuid\":\"e49f9ecf-8ce2-4873-8274-b7ef7d539a52\",\"changeDate\":null,\"comments\":null,\"additionalInfo\":null,\"changes\":[{\"id\":0,\"field\":\"status\",\"fromValue\":\"\",\"toValue\":\"Status(version=0, id=1, name=active, authorService=AuthorService(version=0, id=1, name=accounting))\"},{\"id\":0,\"field\":\"function\",\"fromValue\":\"\",\"toValue\":\"Function(version=0, id=1, name=info, authorService=AuthorService(version=0, id=1, name=accounting))\"},{\"id\":0,\"field\":\"name\",\"fromValue\":\"\",\"toValue\":\"reports.txt\"},{\"id\":0,\"field\":\"authorService\",\"fromValue\":\"\",\"toValue\":\"AuthorService(version=0, id=1, name=accounting)\"},{\"id\":0,\"field\":\"owner\",\"fromValue\":\"\",\"toValue\":\"Owner(version=0, id=1, guid=cb36910c-5123-4ca4-aa96-d560bcfd38de)\"},{\"id\":0,\"field\":\"id\",\"fromValue\":\"0\",\"toValue\":\"10\"},{\"id\":0,\"field\":\"uuid\",\"fromValue\":\"\",\"toValue\":\"7925d481-c5dc-4193-b7cb-a441913d93f8\"}]}",
"scheme" : "http",
"host" : "localhost",
"port" : 11887,
"loggedDateString" : "2020-04-02T17:56:20Z",
"queryParams" : { }
}
мой тестовый код выглядит следующим образом:
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"spring.cloud.config.enabled=false"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@AutoConfigureMockMvc
@SpringApplicationConfiguration(classes = {ServiceDocumentApplication.class}, initializers = {SaveFileTest.TestInit.class})
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
@Slf4j
public class SaveFileTest {
@ClassRule
public static MySQLContainer db = new MySQLContainer();
@Rule
public WireMockRule changelogService = new WireMockRule(11887);
@Rule
public WireMockRule authRule = new WireMockRule(8901);
@Autowired
private WebApplicationContext webCtx;
@Autowired
private DocumentService docService;
@Autowired
private DocumentFileRepository docFileRepo;
private MockMvc mvc;
@Before
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(webCtx).build();
authRule.stubFor(post(urlEqualTo("/oauth/token"))
.willReturn(aResponse()
.withStatus(200)
.withBody("{\"access_token\": \"ken sent me\", \"expires_in\": 200000}")));
}
@Test
public void givenDocumentThatDoesNotExist_whenSaving_thenReturn500() throws Exception {
final String testFilename = "new-test-doc.txt";
final ClassPathResource newFileResource = new ClassPathResource(String.format("save-document/%s", testFilename));
final byte[] newFileContent = Files.readAllBytes(Paths.get(newFileResource.getURI()));
final String documentUuid = UUID.randomUUID().toString();
final String authorUuid = UUID.randomUUID().toString();
final MockMultipartFile uploadFile = new MockMultipartFile("file", testFilename,
MediaType.TEXT_PLAIN_VALUE, newFileContent);
final MockMultipartFile authorPart = new MockMultipartFile("authorGuid", "authorGuid",
MediaType.TEXT_PLAIN_VALUE, authorUuid.getBytes(StandardCharsets.UTF_8));
final MockMultipartFile documentStatus = new MockMultipartFile("documentStatus",
"new".getBytes(StandardCharsets.UTF_8));
mvc.perform(fileUpload(String.format("/document/saveFile/%s", documentUuid))
.file(uploadFile)
.file(authorPart)
.file(documentStatus))
.andDo(print())
.andExpect(status().isInternalServerError());
authRule.resetAll();
}
@Test
public void givenDocumentThatExists_whenUpdated_thenReturn200AndSendChangeLogstoService() throws Exception {
final String ownerUuid = UUID.randomUUID().toString();
final String authorUuid = UUID.randomUUID().toString();
// setup - create dcoument
final Document createdDoc = docService.createDocument("reports.txt", "active", "info", ownerUuid, "accounting", authorUuid);
//setup - wiremock config
changelogService.stubFor(post(urlEqualTo("/apiv1/registerChanges")).willReturn(aResponse().withStatus(200)));
final String testFilename = "update-doc.txt";
final ClassPathResource updateFileRes = new ClassPathResource(String.format("save-document/%s", testFilename));
final byte[] updateFileContent = Files.readAllBytes(Paths.get(updateFileRes.getURI()));
final MockMultipartFile uploadFile = new MockMultipartFile("file", testFilename,
MediaType.TEXT_PLAIN_VALUE, updateFileContent);
final MockMultipartFile authorPart = new MockMultipartFile("authorGuid", "authorGuid",
MediaType.TEXT_PLAIN_VALUE, authorUuid.getBytes(StandardCharsets.UTF_8));
final MockMultipartFile documentStatus = new MockMultipartFile("documentStatus",
"updated".getBytes(StandardCharsets.UTF_8));
// perform call
mvc.perform(fileUpload(String.format("/document/saveFile/%s", createdDoc.getUuid()))
.file(uploadFile)
.file(authorPart)
.file(documentStatus))
.andDo(print())
.andExpect(status().isOk());
// verify
final DocumentFile savedFile = docFileRepo.findByDocumentIdAndDeletedFalse(createdDoc.getId());
assertNotNull(savedFile);
assertNotNull(savedFile.getFile());
assertArrayEquals(updateFileContent, savedFile.getFile().getData());
await().atMost(20, TimeUnit.SECONDS).untilAsserted(() -> {
changelogService.verify(1, postRequestedFor(urlEqualTo("/apiv1/registerChanges")));
authRule.verify(postRequestedFor(urlEqualTo("/oauth/token")));
});
}
public static class TestInit implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
final MockPropertySource mockProps = new MockPropertySource();
mockProps.setProperty("spring.datasource.url", db.getJdbcUrl());
mockProps.setProperty("spring.datasource.username", db.getUsername());
mockProps.setProperty("spring.datasource.password", db.getPassword());
applicationContext.getEnvironment().getPropertySources().addFirst(mockProps);
}
}
}