samedi 2 mai 2020

findByID method of JPA returning different object than what was defined in Integration test method

I created one testLobby object of Lobby class in my integration test. While fetching the object in my service layer by id, I believe it's giving me a copy of the testLobby object and not the original one. And any changes on lobby object in service layer is not reflecting in the lobby object created in the integration test.

My test class with some print statement

    @Test
public void addUserToLobby(){

    System.out.println("tostring->"+lobbyTest.toString());
    System.out.println("before ->"+lobbyTest.getPlayerIds().size());
    User newUser = new User();
    newUser.setUsername("user2");
    newUser.setPassword("password");

    newUser = userService.createUser(newUser);
    System.out.println("new user ->"+newUser.getId());

    lobbyService.addPlayerToLobby(lobbyTest.getId(),newUser.getId());
    System.out.println("after->"+lobbyTest.getPlayerIds().size());
    assertEquals(lobbyTest.getPlayerIds().size(),2);
}

My service method to test

    public Lobby getLobby(Long id) {
    Optional<Lobby> optionalLobby = lobbyRepository.findById(id);
    if (!optionalLobby.isPresent()) {
        throw new LobbyException(String.format("Could not find lobby with id %d.", id));
    }
    return optionalLobby.get();
}



    public void addPlayerToLobby(long id, long userId){
    Lobby lobby = getLobby(id);

    System.out.println("to string service->"+lobby.toString());
    System.out.println("service ->"+lobby.getId()+" "+lobby.getPlayerIds().size());
    lobby.getPlayerIds().add(userId);
    saveOrUpdate(lobby);

    System.out.println("service3->"+lobby.getId()+" "+lobby.getPlayerIds().size());
}

    public void saveOrUpdate(Lobby updateLobby){
    lobbyRepository.save(updateLobby);
    lobbyRepository.flush();
    System.out.println("service method ->"+updateLobby.getId()+" "+updateLobby.getPlayerIds().size());
}

Output of print statement

tostring->entity.Lobby@2bf5b2d1 --> hex of object in test
before ->1
new user ->3
to string service->entity.Lobby@1d4bb56c --> hex of object in service layer
service ->2 1
service method ->2 2
service3->2 2
after->1

While printing the hex of the object in my test class and service class, both are different. And any operation in service layer object is not reflecting in test layer.

How to return the same object by using findById?

Aucun commentaire:

Enregistrer un commentaire