【问题标题】:Running JUnit test on Controller results in UnsatisfiedDependencyException在 Controller 上运行 JUnit 测试会导致 UnsatisfiedDependencyException
【发布时间】:2017-06-04 13:24:10
【问题描述】:

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

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();
        }

UnitTest.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 {

    }

【问题讨论】:

    标签: java spring gradle junit


    【解决方案1】:

    我想通了,原来是我在 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 两个文件中的代码合并到一个文件 AppConfig.java 下的 com.pckg 包下。

    一切都很好,现在正在工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多