javaspringencodingmockmvc

Encoding problem in Spring Boot MockMvc tests


I'm implementing integration tests for my Spring Boot application using MockMvc. The problem is that I need to use russian characters in my request/response bodies and they keep changing to unreadable symbols

Here's my config:

@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");
    }

Test 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());
    }

Response:

Expected :ТРМ-001
Actual   :ТРÐ-001

Test 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));
    }

Result:

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 = []

Tried to set encoding in test class properties / for objectMapper / for mockMvc - none of that worked for me Also tried doing it in my migration files which actually doesn;t make sense because characters in request are already messed up

Upd Forgot to mention that the app works just fine when testing with Swagger or Postman


Solution

  • After trying every possible solution I stumbled upon russian forums where my problem was discussed consistently. So, changing Windows default locale to UTF-8 worked for me in the end Here's a short guide: https://exploratory.io/note/exploratory/Enabling-UTF-8-on-Windows-hYc3yWL0