verify
의 Mockito의 JavaDocs 메소드는 this interesting article에 대한 질문과 대답에 링크되어 있습니다. 나는 특별히 "stubbed 상호 작용 가 암시 적으로 확인 된"으로 약간 잃어 버렸습니다.Mockito 상호 작용 확인 결과 확인
- HQL 쿼리가 제대로 구성되었는지 :의 나는이 방법에 대해 확인할 수있는 것을 보자, 이제이 클래스
이class FooDao { private EntityManager entityManager; public FooDao(EntityManager entityManager) { this.entityManager = entityManager; } public List<Foo> findFooByName(String name, String otherParam) { String hql = "SELECT f FROM Foo f WHERE 1 = 1 "; if(name != null) { hql += " AND f.name = :name"; } if(otherParam != null) { hql += " AND f.other = :otherParam"; } TypedQuery<Foo> query = this.entityManager.createQuery(hql, Foo.class); if(name != null) { query.setParameter("name", name); } if(otherParam != null) { query.setParameter("otherParam", otherParam); } return query.getResultList(); } }
가 상상 :
의 예로 들어 보자 주어진 매개 변수에 대해.
- 매개 변수가 쿼리 개체에 올바르게 바인딩되어 있습니다.
- 그 결과는 내가 기대하는 것입니다.
먼저 실제 데이터베이스에 액세스하고 싶지 않기 때문에 EntityManager
개체를 조롱합니다.
@InjectMocks
private FooDao dao;
@Mock
private EntityManager entityManager;
지금, 나는 그냥이 같은 것을 추가 할 수
@Mock
private TypedQuery<Foo> mockQuery;
@Test
public void testFindFooByName() {
List<Foo> stubData = stubData(); // Method definition omitted for brevity
// Return the custom mockedQuery with the entityManager
Mockito.when(mockQuery.getResultList()).thenReturn(stubData);
Mockito.when(entityManager.createQuery(Mockito.anyString(),
Mockito.eq(Foo.class)))
.thenReturn(mockQuery);
List<Foo> actual = dao.findFooByName("foobar", null);
// Now what should I check?
}
그래서, 지금 문제는 확인하는 것입니다. assertEquals(stubData, actual)
을 추가하면 테스트가 성공적으로 완료됩니다.
또한 추가 할 수 있습니다
Mockito.verify(entityManager).createQuery(expectedSql, Foo.class);
Mockito.verify(mockQuery).setParameter("name", "foobar");
첫 번째 검증은 HQL 쿼리가 제대로 구축되어 있는지 확인하고 두 번째 매개 변수가 올바르게 쿼리에 바인딩되었는지 확인합니다. 이러한 검증이 필요합니까 아니면 결과만으로 충분하다고 주장합니까?
이에 혼란을 추가 여부를 결정, 코드 커버리지 번호를 검토하는 것은 내가 –