JUnit 测试使用 @Modifying 注释的本机查询

JUnit testing native queries annotated with @Modifying

我正在制作一个 SpringBoot 应用程序,其中我有两个具有多对多关系的 classes:User 和 Plant。我正在使用 MySQL 数据库,其中我有 tables usersplants 和一个连接的 table 两个 classes user_plants.

然后我有一个 UserRepository 接口,我在其中定义了一个从 user_plants table:

中删除条目的方法
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

    @Modifying
    @Query(value = "DELETE FROM user_plants WHERE user_id = ?1 AND plant_id = ?2", nativeQuery = true)
    void deletePlantById(int userId, int plantId);
}

这个方法后来在UserService中使用class:

@Service
public class UserService {
  private final UserRepository userRepository;

   @Autowired
   public UserService(UserRepository userRepository){
       this.userRepository = userRepository;   }

   @Transactional
   public void deletePlant(int userId, int plantId){
       userRepository.deletePlantById(userId, plantId);
   }}

我最近开始学习单元测试,我正在尝试为 UserRepository 编写单元测试。我设法成功测试了所有默认的 JpaRepository 方法,例如 getByIdfindAll 等。但是,对我实现的方法的测试总是失败。

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class UserRepositoryTest {

   @Autowired
   private UserRepository userRepository;
   private User user;

   @BeforeEach
   public void setUp(){
       Set<Plant> plantsSet = new LinkedHashSet<>();
       plantsSet.add(new Plant(5, "Monstera"));
       user = new User(1, "Alice", plantsSet);
       userRepository.save(user);
   }

   @AfterEach
   public void clean(){
       userRepository.deleteAll();
       user = null;
   }

   @Test
   void givenPlantIdAndUserIdShouldDeletePlantOfThatIdFromUserPlants() {
       userRepository.deletePlantById(1, 5);
       assertTrue(user.getOwnedPlants().isEmpty());
   }

我手动测试了这个方法,我可以看到它工作正常 - 对数据库的更改是按照我想要的方式进行的。那么为什么测试会失败呢?我应该怎么写呢?

当你执行这一行时

userRepository.deletePlantById(1, 5);

您正在删除数据库中的用户工厂,但对象 user 中仍有用户工厂列表。

为了检查删除是否正确完成,您必须执行查询以通过用户 ID 查找用户植物。我假设接口 UserPlantRepository 存在。

@Test
void givenPlantIdAndUserIdShouldDeletePlantOfThatIdFromUserPlants() {
   userRepository.deletePlantById(1, 5);
   assertTrue(userPlantRepository.findByUserId(1)).isEmpty()
}