用于本机查询junit

ql3eal8s  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(101)

这是我的存储库类:

@Repository
public interface EntitlementRepository extends JpaRepository<Entitlement, Long> {

    Entitlement findByIdAndActiveTrue(Long entitlementId);

    List<Entitlement> findByIdInAndActiveTrue(Collection<Long> entitlementIds);

    List<Entitlement> findByIdIn(Collection<Long> entitlementIds);

    @Modifying
    @Query(value = "UPDATE ENTITLEMENT set RESTRICTION_LEVEL=:restrictionLevel where ID =:entitlementId", nativeQuery = true)
    void updateRestrictionLevel(@Param("restrictionLevel") String restrictionLevel, @Param("entitlementId") Long entitlementId);
}

这是我的仓库类junit:

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
public class EntitlementRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private EntitlementRepository repository;

    @Test
    public void testUpdate() {
        Entitlement entitlementToAdd = anEntitlement("APPROVER1", "APPROVER2", "APPROVER3", null);
        Entitlement savedEnt = repository.save(entitlementToAdd); // create Entitlement with restriction null

        repository.updateRestrictionLevel("LEVEL11", savedEnt.getId()); // update restriction level 

        Entitlement updatedEnt = repository.findByIdAndActiveTrue(savedEnt.getId());
        assertThat(updatedEnt.getRestrictionLevel()).isEqualTo("LEVEL11");
    }
}

restrictionLevel没有更新。它保持为空。因此,assert语句失败。

jaxagkaj

jaxagkaj1#

这类似于How to test method from repository which marked as @Modifying?
通过添加一个entityManager.clear()解决了这个问题;

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
public class EntitlementRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private EntitlementRepository repository;

    @Test
    public void testUpdate() {
        Entitlement entitlementToAdd = anEntitlement("APPROVER1", "APPROVER2", "APPROVER3", null);
        Entitlement savedEnt = repository.save(entitlementToAdd); // create Entitlement with restriction null

        repository.updateRestrictionLevel("LEVEL11", savedEnt.getId()); // update restriction level 
        entityManager.clear();
        Entitlement updatedEnt = repository.findByIdAndActiveTrue(savedEnt.getId());
        assertThat(updatedEnt.getRestrictionLevel()).isEqualTo("LEVEL11");
    }
}

相关问题