I am using H2 as my testing database.  My testing code looks like as follows:
@Test
    public void shouldBeAbleToUpdateHrUserNameByUserId(){
        final User user = userRepository.findOne(“2”);
        final String originalHrUsername = user.getHrUserName();
        final String UPDATED_HR_USERNAME = “luketong”;
        assertThat(originalHrUsername, is(ORIGINAL_HR_USERNAME));
        userRepository.updateHrUsernameBy(“2”, UPDATED_HR_USERNAME);
        final User updatedUser = userRepository.findOne(“2”);
        assertNotNull(updatedUser);
        final String updateHrUsername = updatedUser.getHrUserName();
        assertThat(updateHrUsername, is(UPDATED_HR_USERNAME));
    }
The test case failed in the last assert. I tried to debug it and to my surprise I found both updatedUser  and user point to the same memory address. If this is the case of course I can’t get the assertion passed. But the question is why they point to the same memory address?
DataJpaTest not work1
A: According to https://stackoverflow.com/questions/45617040/datajpatest-fail-to-update-in-unit-test in order to clear the underlying persistence context after executing the modifying query, you need to add an extra attribute of the annotation @Modifying as @Modifying(clearAutomatically = true)
After the change, the two user instances no longer point to the same memory address as shown below, and my test case  passed.

DataJpaTest not work2

Please be noted in my original approach, the update SQL statement is displayed in console.
Advertisements