如何为@Query方法编写JUnit测试用例

时间:2018-05-03 11:03:22

标签: unit-testing spring-data-jpa junit4

我知道如何为JUnit此类方法编写findBySInvestigatorName(String SInvestigatorName)测试用例。但我想知道如何为@Query方法编写测试用例。任何人都可以告诉我如何编写以下方法的测试用例?

@Repository
public interface InvestigatorRepository extends JpaRepository<Investigator, Integer> {

    @Query("select new map(invest.sInvestigatorName as sInvestigatorName)"
            + " from Investigator invest where invest.nInstId=60")
    Set<Investigator> findSinvestigatorName();

}

我试过这个

@RunWith(SpringRunner.class)
@DataJpaTest
public class TestInvestigatorRepository {

    @Autowired
    public TestEntityManager testEm;

    @Autowired
    InvestigatorRepository investRepo;

    @Test
    public void testFindSinvestigatorName() {

        Investigator invest = new Investigator();
        invest.setsInvestigatorName("abc");
        invest.setnInstId(60);

        Investigator saveInDb = testEm.merge(invest);

       Set<Investigator> getFromDb = investRepo.findSinvestigatorName();

      assertEquals(saveInDb.getsInvestigatorName(), getFromDb);

    }

测试失败

java.lang.AssertionError: expected:<abc> but was:<[{sInvestigatorName=abc}]>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:118)
    at org.junit.Assert.assertEquals(Assert.java:144)

1 个答案:

答案 0 :(得分:1)

除了您将StringSet<Investigator>进行比较外,您的测试几乎没问题。

将您的断言更改为

assertEquals(saveInDb.getsInvestigatorName(), getFromDb.iterator().next().getsInvestigatorName());

注意:您可能需要查看AssertJ。它允许您为集合编写更好的断言