Spring Data + JPA등을 쓰면서도 간혹 Native의 Sql을 사용하는 경우가 있다.
이런경우에 대한 Test코드는 다음과 같다.
...
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
...
@RunWith(MockitoJUnitRunner.class)
public class XXXXFindNativeQueryServiceTest {
@InjectMocks
private XXXXFindNativeQueryService service;
@Mock
private EntityManager entityManager;
@Test
public void test_테스트용_메소드() throws Exception {
Object[] resultObject = {new Long(1), new Long(2), new Long(3)};
Query mockQuery = mock(Query.class);
when(mockQuery.getSingleResult()).thenReturn(resultObject);
when(entityManager.createNativeQuery(anyString())).thenReturn(mockQuery);
service.recount();
}
}