'Why doesn't nickname change?

I'm writing a test code using MockMVC for API to modify member information, but I think put doesn't work in MockMVC, but I don't know why. I can't solve this error.

[Member Controller]

@PutMapping("/member")
@ResponseStatus(HttpStatus.OK)
public void updateBasicInfo(@Valid @RequestBody MemberUpdateDto memberUpdateDto) throws Exception {
    memberService.update(memberUpdateDto);
}

[UpdateDto]

@Data
public class MemberUpdateDto {
    private Optional<String> nickname;

    public MemberUpdateDto(Optional<String> updateNickname) {
        this.nickname = updateNickname;
    }
}

[Test_Code]

@Test
    public void updateMember() throws Exception{
        //given
        String signUpData = objectMapper.writeValueAsString(new MemberSignUpDto(email, nickname, password));
        signUp(signUpData);
        String accessToken = getAccessToken();
        Map<String, Object> map = new HashMap<>();
        map.put("nickname",nickname+"change");

        //when
        mockMvc.perform(
                        put("/member")
                                .header(accessHeader, BEARER+accessToken)
                                .contentType(MediaType.APPLICATION_JSON)
                                .content(objectMapper.writeValueAsString(map)))
                .andExpect(status().isOk());


        //then
        Member member = memberRepository.findByEmail(email)
            .orElseThrow(() -> new Exception("Member does not exist."));
        assertThat(member.getNickName()).isEqualTo(nickname+"change");
    }

[Error]

MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /member
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBY2Nlc3NUb2tlbiIsImV4cCI6MTY1Mjk4MjIxNSwiZW1haWwiOiJzZEBkYWYuY29tIn0.-iFV9zJtb41S35nCe5ThzewkJg71zS4EpWTC3dlyYPvQNCo1y8oBRWKAvyX8eDVwQ5Kh4uaaSkjU7Zq6vItWvw", Content-Length:"25"]
             Body = {"nickname":"sdfachange"}
    Session Attrs = {}

Handler:
             Type = studyboard.studyboard.controller.MemberController
           Method = studyboard.studyboard.controller.MemberController#updateBasicInfo(MemberUpdateDto)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageConversionException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2022-05-19 21:10:15.383  INFO 5676 --- [           main] p6spy                                    : #1652962215383 | took 2ms | rollback | connection 3| url jdbc:mysql://127.0.0.1:3306/studyboard

;
2022-05-19 21:10:15.386  INFO 5676 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@5bc9ba1d testClass = MemberControllerTest, testInstance = studyboard.studyboard.member.MemberControllerTest@62c02089, testMethod = 회원정보_수정_성공@MemberControllerTest, testException = org.opentest4j.AssertionFailedError: 
expected: "sdfachange"
 but was: "sdfa", mergedContextConfiguration = [WebMergedContextConfiguration@1021f6c9 testClass = MemberControllerTest, locations = '{}', classes = '{class studyboard.studyboard.StudyboardApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@2e32ccc5, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@4b3fa0b3, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4ef782af, [ImportsContextCustomizer@7516e4e5 key = [org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration, org.springframework.boot.test.autoconfigure.web.reactive.WebTestClientAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4167d97b, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@68f1b17f, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@5c669da8, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@473b46c3], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]

org.opentest4j.AssertionFailedError: 
expected: "sdfachange"
but was: "sdfa"
Expected :"sdfachange"
Actual   :"sdfa"

The changed nickname information is properly entered in the map, and if you look at the error code, it seems that the PUT request is being made properly with Request, but the nickname information is not changed.

I want to change the "nickname", but it doesn't change. What should I do? Please Let me know how I can solve this error.

[MemberService]

@Override
public void update(MemberUpdateDto memberUpdateDto) throws Exception{
    Member member = memberRepository.findByEmail(SecurityUtil.getLoginUsername()).orElseThrow(() -> new Exception("Member does not exist."));
    memberUpdateDto.getNickname().ifPresent(member::updateNickName);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source