JPA repository.save is Null (NullPointerException) - feat. @RunWith & @SpringBootTest & @DataJpaTest
Spring
While I was creating a test case for my JPArepository to save a post in my toy project:
@Autowired
private ProjectRepository projectRepository;
@Test
public void createPost(){
//given
projectRepository.save(Project.builder()
.title("hi")
.content("testing")
.build());
//when
List<Project> projectList = projectRepository.findAll();
//then
Project project = projectList.get(0);
assertThat(project.getTitle().equals("hi"));
assertThat(project.getContent().equals("testing"));
}
At the createPost function, NullPointerException occurred.
Why? My repository has no problem…?
Turns out projectRepository, which has been DIed, is null.
But why is it null?
Because there is no @RunWith annotation. Whenever conducting test with SpringBootTest, you need to use the SpringRunner class, which is inherited from JUnit.
So bean is not DIed properly, causing NullPointer error.
@RunWith(SpringRunner.class)
- When JUnit framework conducts test, runs the built-in Runner class
- If you want to use @SpringBootTest annotation, need to use @RunWith(SpringRunner.class), which inherits JUnit SpringJUnit4ClassRunner class.
- 스프링과 테스트 통합
@SpringBootTest
- for an integrated test
- Integrates individual 단위 tests into 1 integrated test
- But it loads all the application’s settings so as the app scales, it becomes slower
- 스프링 부트를 띄우고 테스트 (이거 없으면 @Autowired does not work)
@Transactional
- 반복 가능한 test 지원
- For each test run, starts transaction and when test finishes, rolls back the transaction forcefully
@DataJpaTest
- for JPA test
- When individual 단위 test ends, automatically rolls back the DB
- Uses in-memory DB
- If want to test in the actual DB, add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) annotation
Summary
Annotation | Explanation | Bean |
---|---|---|
@SpringBootTest | 통합 테스트, 전체 | Bean 전체 |
@WebMvcTest | 단위 테스트, Mvc 테스트 | MVC 관련된 Bean |
@DataJpaTest | 단위 테스트, Jpa 테스트 | JPA 관련 Bean |
@RestClientTest | 단위 테스트, Rest API 테스트 | 일부 Bean |
@JsonTest | 단위 테스트, Json 테스트 | 일부 Bean |
[Test annotations]
Reference: https://n1tjrgns.tistory.com/224