I'm trying to create a repository test with the Spring @DataJpaTest annotation. Even with the simple demo project I receive a IllegalArgumentException: Unknown entity. Do I miss something?
I'm using the Baeldung example for testing with Spring. There is a simple @DataJpaTest and I applied it to my code. When running the test I received a IllegalArgumentException: Unknown entity exception, that repository itself can not be found. So I created a demo project with minimal required classes and still got this error.
the entity class:
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class DemoEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; // getter and setter } the repositiory class:
@Repository public interface DemoRepository extends JpaRepository<DemoEntity, Long> { Optional<DemoEntity> findByName(String name); } and the test class:
@RunWith(SpringRunner.class) @DataJpaTest public class DemoRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private DemoRepository repository; @Test public void test() { DemoEntity demo = new DemoEntity() {{ setName("Tim"); }}; entityManager.persistAndFlush(demo); Optional<DemoEntity> result = repository.findByName("Tim"); assertThat(result.isPresent()).isTrue(); } } This test results in the exception:
java.lang.IllegalArgumentException: Unknown entity: com.example.demo.repositories.DemoRepositoryTest$1 at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:804) at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785) at org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.persist(TestEntityManager.java:93) at org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.persistAndFlush(TestEntityManager.java:131) at com.example.demo.repositories.DemoRepositoryTest.test(DemoRepositoryTest.java:31) I'm using Spring Boot Starter 2.1.1 and Java 10.