我正在尝试创建一个Spring Boot测试类,该类应该创建Spring上下文并自动连接服务类以供我测试。
这是我得到的错误:
原因: org.springframework.beans.factory.NoSuchBeanDefinitionException:否 类型的合格豆 可用的“ 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());
}
为什么找不到实现?
答案 0 :(得分:2)
@DataJpaTest
注释不会使服务加载到应用程序上下文中。摘自Spring文档:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test
您可以使用@DataJpaTest批注来测试JPA应用程序。默认情况下,它将扫描@Entity类并配置Spring Data JPA存储库。如果在类路径上有嵌入式数据库,它也将配置一个。常规@Component bean不会加载到ApplicationContext中。
您可以使用@SpringBootTest
注释代替DataJpaTest
。希望有帮助!