Reputation: 23
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.
Upvotes: 1
Views: 1149
Reputation: 26878
The problem is due to the way you are creating the instance of DemoEntity
:
DemoEntity demo = new DemoEntity() {{
setName("Tim");
}};
Don't use the double-brace initialization syntax and it should work fine.
You are creating a subclass of DemoEntity
this way. This is what the error message also indicates with the $1
at the end
See https://stackoverflow.com/a/27521360/40064 for more info on why this is a bad idea anyway.
Upvotes: 3