Issue
I have a problem about running some tests through JUnit in my Spring Boot application.
When I tried to run any test of repositorytest, I got the issue shown below.
org.junit.runners.model.InvalidTestClassError: Invalid test class 1. Test class should have exactly one public zero-argument constructor
I also defined @Runwith annotation but it didn't help me fix my issue.
import lombok.RequiredArgsConstructor;
import org.junit.Test;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
@DataJpaTest
@RequiredArgsConstructor
public class CategoryRepositoryTests {
private final CategoryRepository categoryRepository;
@Test
public void givenCategoryObject_whenSave_thenReturnSavedCategory() {
// given - precondition or setup
Category category = Category.builder().name(CategoryType.COMIC.getValue()).build();
// when - action or the behaviour that we are going test
Category savedCategory = categoryRepository.save(category);
// then
assertThat(savedCategory.getId()).isGreaterThan(0);
assertThat(savedCategory).isNotNull();
}
}
How can I fix it?
Solution
After I defined @RunWith(SpringRunner.class)
, the issue disappeared.
Here is the solution shown below.
@DataJpaTest
@RunWith(SpringRunner.class)
public class CategoryRepositoryTests {
@Autowired
private CategoryRepository categoryRepository;
}
Answered By - S.N
Answer Checked By - Terry (JavaFixing Volunteer)