我正在使用 MockMvc 为我的 Spring Boot 应用程序实现集成测试。问题是我需要在请求/响应正文中使用俄语字符,并且它们不断更改为不可读的符号
这是我的配置:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = InfoApplicationConfig.class)
@TestPropertySource(properties = {"spring.config.location=classpath:application-it.yml"})
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class TerminalControllerIT {
@Autowired
MockMvc mockMvc;
@LocalServerPort
private int port;
private String baseUrl = "http://localhost";
private final String validTerminalId = "eee00000-0000-0000-0000-000000000000";
private final String invalidTerminalId = "abc00000-0000-0000-0000-000000123456";
private NewTerminalDto testSubject;
@Autowired
private static ObjectMapper objectMapper;
@Autowired
private TerminalRepository terminalRepository;
@BeforeEach
public void setUp() {
testSubject = NewTerminalDto.builder().country("Россия").region("Москва").city("Москва")
.street("Ленина").buildingNumber("12A")
.roomNumber("101").terminalCoordinate("55.7558,37.6176")
.postCode("123456").terminalNumber("123")
.isClosed(false).cashDepositWithdrawal(false).moneyTransfer(true).payment(true).nfc(true)
.banknotesPerPack(100)
.biometrics(false).encashmentService(true).cashDeposit(true)
.openingTime("08:00")
.closingTime("18:00")
.build();
baseUrl = baseUrl.concat(":" + port).concat("/api/v1/info-service/terminals");
}
测试1:
@Test
@DisplayName("Should return terminal by id")
void getTerminalInfoByIdPositiveTest() throws Exception {
MvcResult result = mockMvc.perform(get(baseUrl + "/" + validTerminalId)
.characterEncoding("UTF-8")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
String jsonResponse = result.getResponse().getContentAsString();
TerminalGetResponse actualResponse = objectMapper.readValue(jsonResponse, TerminalGetResponse.class);
assertNotNull(actualResponse);
assertNotNull(actualResponse.getTerminalNumber());
assertNotNull(actualResponse.getRegion());
assertEquals("ТРМ-001", actualResponse.getTerminalNumber());
assertEquals("Москва", actualResponse.getRegion());
}
回应:
Expected :ТРМ-001
Actual :ТРÐ-001
测试2:
@Test
@DisplayName("Adding branch")
void addBranch() throws Exception {
BranchPayload body = BranchStubs.createBranchPayload(0);
mockMvc.perform(post(baseUrl)
.content(objectMapper.writeValueAsBytes(body))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.characterEncoding("UTF-8"))
.andExpect(status().isOk());
BankBranchesModel bankBranchesModel = BankBranchesModel.builder().branchNumber(body.getBranchNumber()).build();
assertNotNull(bankBranchesRepository.findOne(Example.of(bankBranchesModel)).orElse(null));
}
结果:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/v1/info-service/branches
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"907"]
Body = {"branchNumber":"8500","country":"??????","region":"?????????? ???????","city":"????????","street":"???????????","buildingNumber":"5","postCode":"117997","branchCoordinate":"55.696225, 37.544539","ramp":true,"phoneNumber":"74955555550","isClosed":false,"openingTime":"00:00","closingTime":"23:55","dayOfWeek":["???????????","???????","?????","???????","???????"],"currencyExchange":true,"foreignCurrency":true,"moneyTransfer":true,"cashWithdrawal":true,"payment":true,"replenishCard":true,"replenishAccount":true,"hasDeposit":true,"hasCredit":true,"consultation":true,"insurance":true,"bik":"044525220","kpp":"773643002","inn":"7707083890","paymentAccount":"40702810562000000000","correspondentAccount":"30101810400000000225","bankNameFull":"?? «FinTech Bank»","okpo":"09610477","ogrn":"1027700057410","swift":"LIBBRUMM007"}
Session Attrs = {}
...
MockHttpServletResponse:
Status = 400
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = {"bankNameFull":"must match \"^(?!\\s*$)[0-9A-Za-z?-??-? !\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_{|}~]{1,30}$\""}
Forwarded URL = null
Redirected URL = null
Cookies = []
尝试在测试类属性/objectMapper/mockMvc 中设置编码 - 这些都不适合我 还尝试在我的迁移文件中执行此操作,这实际上没有意义,因为请求中的字符已经混乱了
更新忘了提及,在使用 Swagger 或 Postman 进行测试时,该应用程序工作得很好
在尝试了所有可能的解决方案之后,我偶然发现了俄罗斯论坛,在那里我的问题得到了一致的讨论。因此,将 Windows 默认区域设置更改为 UTF-8 最终对我有用 这是一个简短的指南:https://exploratory.io/note/exploratory/Enabling-UTF-8-on-Windows-hYc3yWL0