【问题标题】:Repository Test in spring boot leads to Unknown entity ExceptionSpring Boot 中的存储库测试导致未知实体异常
【发布时间】:2019-07-19 16:11:59
【问题描述】:
  • com.mohendra.user

    • 服务器
      • Application.class //主类
    • package2

    • 包3

        • Campaigns.class
        • SmsDomainPackage.class
      • 存储库
        • CampaignRepository.class

以上是我的文件夹结构,我正在尝试使用 spring dataJpaTest 测试 CampaignRepository , 我已经写了以下测试

@ComponentScan(basePackages = "com.mohendra.user")
@EntityScan(basePackageClasses = SmsDomainPackage.class)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@DataJpaTest
@RestClientTest
public class CampaignRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private CampaignRepository repository;

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void findByCode() {
        Campaigns campaigns = new Campaigns();
        campaigns.setName("Name");
        campaigns.setCode("HELP123");
        campaigns.setStartDate(new Date());
        campaigns.setEndDate(new Date());
        this.entityManager.persist(campaigns);

        Campaigns campaigns1 = repository.findByCode("HELP123");
        System.out.println();
    }
}

测试给出了一个例外

java.lang.IllegalArgumentException:未知实体: com.mohendra.user.package3.domain.Campaigns

如您所见,我还使用了@ComponentScan,并且我还使用了@EntityScan 来尝试扫描包中的实体,但它们都不起作用。 我无法更改我的文件夹结构以使其成为标准,因为它不是我的项目。有解决办法吗?

【问题讨论】:

    标签: unit-testing spring-boot spring-data-jpa integration-testing junit4


    【解决方案1】:

    Application 类应该在根包中。这样你就不需要任何 @CompontenScan 或 @EntityScan,因为 Spring Boot 会扫描你的根包下的所有内容

    因此我建议将Application.class 放入包中com.mohendra.user

    你必须决定你想要哪个测试片。你有三个:

    @SpringBootTest(classes = Application.class)
    @DataJpaTest
    @RestClientTest
    

    但我假设你只想要@DataJpaTest

    【讨论】:

    • 我不能这样做,这不是我提到的我的项目。就没有别的办法了吗?
    • 我更新了我的答案,因为我看到您的测试中有多个测试注释。您应该阅读有关 Spring Boot 中的测试是否有效:docs.spring.io/spring-boot/docs/current/reference/html/…
    • 什么?它只是在另一个包中移动一个类。这将是 Spring Boot 标准。这是一个更好的变化。
    • 我读过,但我的理解是,@springboottest 是在应用程序上下文中扫描运行测试,然后你把 datajpattest 放到测试实体,restclient 用于其余模板,是吗三个都放错了吗?
    • 是的,这是错误的,因为例如 DataJpaTest 仅启动最小存储库和内存数据库,而 SpringBootTest 启动整个环境。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2018-06-26
    • 2023-01-06
    • 2014-05-31
    • 2021-06-24
    • 1970-01-01
    • 2019-01-23
    相关资源
    最近更新 更多