Writing test cases for update JPQL not supported in DataJpaTest

79 views Asked by At
public interface UserRepository extends JPARepository<User, Integer> {

    @Modifying
    @Query("update User u set u.active = false where u.userId = :userId")
    void updateEmployee(Integer userId);

.......
}

I am new to unit testing. So I am trying to write test cases for JPQL using DataJpaTest for the above repository method. Every time my test case failed when I used the following method to test also I could not identify where I was making mistakes. If anyone has a solution it would be really helpful to me. Thanks in Advance.!

In the test case, I wrote, that the field active does not get updated and The value is also null.

@Test
void updateUserRecord(){
    User user = new User();
    user.setUserId(1);
    userRepository.save(user);
    
    userRepository.updateEmployee(user.getUserId());
    
    assertFalse(user.getActive());
} 
1

There are 1 answers

1
Junhyunny On BEST ANSWER

When using @Modifying, @Query annotation, JPA directly update database. Not update persistent context. So your user instance in test code is not updated. You have to re-fetch from database.

I think using entity manager as a helper makes your test code better.

  1. Prepare data with entity manager. After that flush and clear.
  • flush method reflects entities changes in persistent context to database.
  • clear method clears persistent context.
  1. Update user data
  2. Find result from database again.
package com.example.demo;

import com.example.demo.app.User;
import com.example.demo.app.UserRepository;
import jakarta.persistence.EntityManager;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

@DataJpaTest
class DemoApplicationTests {

    @Autowired
    EntityManager entityManager;
    @Autowired
    UserRepository userRepository;

    void flushAndClear() {
        entityManager.flush();
        entityManager.clear();
    }

    @Test
    void updateUserRecord() {
        User user = new User();
        user.setUserId(1);
        entityManager.persist(user);
        flushAndClear();


        userRepository.updateEmployee(user.getUserId());


        User result = entityManager.find(User.class, user.getUserId());
        assertEquals(false, result.getActive());
    }
}