【发布时间】:2020-03-24 08:26:21
【问题描述】:
我正在尝试创建一个 Spring Boot 测试类,它应该创建 Spring 上下文并自动装配服务类以供我测试。
这是我得到的错误:
原因: org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 符合条件的 bean 类型 'com.gobsmack.gobs.base.service.FileImportService' 可用:预期 至少 1 个符合自动装配候选资格的 bean。依赖 注释: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
文件结构:
测试类:
package com.example.gobs.base.service;
import com.example.gobs.base.entity.FileImportEntity;
import com.example.gobs.base.enums.FileImportType;
import lombok.val;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@DataJpaTest
@RunWith(SpringRunner.class)
public class FileImportServiceTest {
@Autowired
private FileImportService fileImportService;
private FileImportEntity entity;
Main 应用程序类:
package com.example.gobs.base;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Used only for testing.
*/
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
FileImportService接口:
package com.example.gobs.base.service;
import com.example.gobs.base.entity.FileImportEntity;
import com.example.gobs.base.enums.FileImportType;
import java.util.List;
public interface FileImportService {
/**
* List all {@link FileImportEntity}s.
实施者:
package com.example.gobs.base.service.impl;
import com.example.gobs.base.entity.FileImportEntity;
import com.example.gobs.base.enums.FileImportType;
import com.example.gobs.base.repository.FileImportRepository;
import com.example.gobs.base.service.FileImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class FileImportServiceImpl implements FileImportService {
@Autowired
private FileImportRepository repository;
@Override
public List<FileImportEntity> listAllFileImportsByType(FileImportType type) {
return repository.findAllByType(type.name());
}
为什么找不到实现?
【问题讨论】:
-
因为您使用的是
@DataJpaTest,它只考虑您应用程序的“数据切片”。 -
您可能不应该使用集成测试来测试该服务。相反,模拟存储库的简单单元测试会更容易编写和维护,运行速度也会更快。
-
啊,问题是它调用了存储库层。有没有办法加载 JPA 和服务层?
-
当然。但你为什么要这样?拥有一个单独的存储库层的要点之一是能够在测试服务层时对其进行模拟,这样服务层的测试就不需要带有测试数据的测试数据库来进行测试。
-
仅供参考,(但我仍然不建议这样做),将
@Import(FileImportServiceImpl.class)添加到您的测试类应该可以使服务可用。您将拥有一个包含所有可用数据层的上下文,以及该特定服务。
标签: java spring-boot testing