在Controller上运行JUnit测试会导致UnsatisfiedDependencyException

时间:2017-01-19 18:03:52

标签: java spring gradle junit

这是我的测试(Gradle)Spring启动项目,允许用户通过RESTful Web服务从数据库检索国家/地区信息。 我可以运行应用程序(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();
        }

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 {

    }

1 个答案:

答案 0 :(得分:4)

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

我的App.java只包含主要方法。

<强> App.java

    @SpringBootApplication
    public class App extends SpringBootServletInitializer {

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

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

<强> AppConfig.java

e.g。

    @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中。

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