java - 在 Controller 上运行 JUnit 测试导致 UnsatisfiedDependencyException

标签 java spring gradle junit

这是我的测试 (Gradle) Spring boot 项目,它允许用户通过 RESTful 网络服务从数据库中检索国家/地区信息。 我可以运行该应用程序 (gradlew bootRun),它按预期工作。但是我在 ServiceControllerUnitTest 上运行的 JUnit 测试抛出异常。我是 Spring 的新手,所以我认为我可能遗漏了一些非常明显的东西,很可能与我的测试配置有关。

enter image description here

build.gradle

    dependencies {

        // Spring Boot
        compile("org.springframework.boot:spring-boot-starter-web")
        compile('org.springframework.boot:spring-boot-starter-web-services')
        compile('org.springframework.boot:spring-boot-starter-data-rest')
        compile("org.springframework.boot:spring-boot-devtools")

        compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.1.4.RELEASE'
        compile 'org.hibernate:hibernate-core:4.3.6.Final'
        compile 'org.hibernate:hibernate-entitymanager:4.3.6.Final'
        compile 'javax.servlet:javax.servlet-api:3.1.0'
        compile 'org.slf4j:slf4j-simple:1.7.7'
        compile 'org.javassist:javassist:3.15.0-GA'
        compile 'mysql:mysql-connector-java:5.1.31'
        compile 'commons-dbcp:commons-dbcp:1.4'  

        // Unit Testing
        testCompile('org.springframework.boot:spring-boot-starter-test')
        testCompile("junit:junit:4.12")
        testCompile("org.mockito:mockito-core:1.10.19")
        testCompile("com.jayway.jsonpath:json-path-assert:0.8.1")

    }

错误

    [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@4e1d422d] to prepare test instance [com.pckg.controller.ServiceControllerUnitTest@2a22ad2b]
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.pckg.controller.ServiceControllerUnitTest': Unsatisfied dependency expressed through field 'controller'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pckg.controller.ServiceController' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)

ServiceController.java

    @RestController
    public class ServiceController {

        @Autowired
        ICountryService countryService;

        @RequestMapping("/country")
        public Country getCountryByName(@RequestParam(value = "name", required = true) String countryName) {

            Country country = countryService.getCountryByName(countryName);
            return country;
        }

        @RequestMapping("/continent")
        public List<Country> getCountryByContinent(@RequestParam(value = "name", required = true) String continent) {

            List<Country> countries = countryService.getCountriesByContinent(continent);
            return countries;
        }

        @RequestMapping("/countries")
        public List<Country> getAllCountries() {
            List<Country> countries = countryService.getAllCountries();
            return countries;

        }
    }

ServiceControllerUnitTest.java

    @Category(UnitTest.class)
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = AppConfig.class)
    public class ServiceControllerUnitTest extends UnitTest {

        private MockMvc mockMvc;

        @Autowired
        private ServiceController controller;

        @Override
        @Before
        public void setUp() {
            super.setUp();
            mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        }

单元测试.java

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = UnitTestConfig.class)
    @WebAppConfiguration
    public abstract class UnitTest {
        @Before
        public void setUp() {
            MockitoAnnotations.initMocks(this);
        }
    }

UnitTestConfig.java

    public class UnitTestConfig extends MockServletConfig {

    }

最佳答案

我想通了,结果是我在 ServiceControllerUnitTest.java 中的 @ContextConfiguration 引用了一个不正确的文件。我在我的应用程序中使用了两个文件 App.javaAppConfig.java(在上面的屏幕截图中)。

我的 App.java 只包含 main 方法。

App.java

    @SpringBootApplication
    public class App extends SpringBootServletInitializer {

        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }

我的 AppConfig.java 包含我的@Bean 声明。

AppConfig.java

例如

    @Bean
    public HibernateTemplate getHibernateTemplate() {
        return new HibernateTemplate(getSessionFactory());
    }

我实际上在 @ContextConfiguration 注释中引用了 AppConfig.java 文件,而不是 App.java 文件。

ServiceControllerUnitTest.java

@Category(UnitTest.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class) // >>>> issue here
public class ServiceControllerUnitTest extends UnitTest {

    private MockMvc mockMvc;

    @Autowired
    private ServiceController controller;

    @Override
    @Before
    public void setUp() {
        super.setUp();
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

我已将 App.java 和 AppConfig.java 文件中的代码合并到 com.pckg 包下的一个 AppConfig.java 文件中。

一切都很好,现在可以正常工作了。

关于java - 在 Controller 上运行 JUnit 测试导致 UnsatisfiedDependencyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41748675/

相关文章:

javascript - 显示图像,该图像在作为服务器运行时在类型文件中输入,但未在浏览器中显示

java - 如何在 Gradle Android 插件中启用 processfork 进行单元测试

java - 找不到 Gradle 构建工具.jar

node.js - 多个 CircleCI 机器/构建(nodejs + java/gradle)

Java for each循环迭代 boolean 数组

java - 如何设置Json schema的类型?

java - java 9 中 javax.activation 包的替代品是什么?

java - Spring : message. 属性文件不起作用

spring - 无需用户登录即可保护 Spring Boot 应用程序

java - HSQLDB 新手,使用 Spring 应用程序和 JavaConfig