简体   繁体   English

JUnit Spring Boot应用程序-无法自动装配字段

[英]JUnit Spring Boot Application - Could not autowire fields

I have small app written with JHipster code generator with Spring Boot on back-end. 我有一个用JHipster代码生成器编写的小型应用程序,后端使用Spring Boot。

For my app I'm trying to write some simple unit/integration tests but I have an error: Could not autowire. No beans of <type> found 对于我的应用程序,我试图编写一些简单的单元/集成测试,但出现错误: Could not autowire. No beans of <type> found Could not autowire. No beans of <type> found . Could not autowire. No beans of <type> found I'm using IntelliJ IDE, latest version. 我正在使用最新版本的IntelliJ IDE。 Here is my piece of code: 这是我的代码:

package com.logate.adminpanel.web.rest;

import com.logate.adminpanel.CrmScoringApp; import
com.logate.adminpanel.repository.CityRepository; import
com.logate.adminpanel.service.CityService; import org.junit.Test;
import org.junit.runner.RunWith; import
org.springframework.boot.test.SpringApplicationConfiguration; import
org.springframework.test.context.ContextConfiguration; import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.inject.Inject;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CrmScoringApp.class)
@WebAppConfiguration 
public class CityRestTest { 

     @Inject
     private CityService cityService;

     @Inject
     private CityRepository cityRepository;

     @Test
     public void test()
     {
         Assert.isNull(null);
     }
 }

I can't figure it out what is the problem here. 我不知道这是什么问题。

Here is my boot application class: 这是我的启动应用程序类:

package com.logate.adminpanel;

import com.logate.adminpanel.config.Constants;
import com.logate.adminpanel.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import   org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.core.env.SimpleCommandLinePropertySource;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;

@ComponentScan
@EnableAutoConfiguration(exclude = {    MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class })
@EnableConfigurationProperties({ JHipsterProperties.class, LiquibaseProperties.class })
public class CrmScoringApp {

    private static final Logger log =    LoggerFactory.getLogger(CrmScoringApp.class);

    @Inject
    private Environment env;

    /**
     * Main method, used to run the application.
     *
     * @param args the command line arguments
     * @throws UnknownHostException if the local host name could not be resolved into an address
     */
     public static void main(String[] args) throws UnknownHostException {
         SpringApplication app = new SpringApplication(CrmScoringApp.class);
         SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
         addDefaultProfile(app, source);
         Environment env = app.run(args).getEnvironment();
    log.info("\n----------------------------------------------------------\n\t" +
            "Application '{}' is running! Access URLs:\n\t" +
            "Local: \t\thttp://127.0.0.1:{}\n\t" +
            "External: \thttp://{}:{}\n----------------------------------------------------------",
        env.getProperty("spring.application.name"),
        env.getProperty("server.port"),
        InetAddress.getLocalHost().getHostAddress(),
        env.getProperty("server.port"));
}

/**
 * If no profile has been configured, set by default the "dev" profile.
 */
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
    if (!source.containsProperty("spring.profiles.active") &&
            !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {

        app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
    }
}

/**
 * Initializes admin_panel.
 * <p>
 * Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
 * <p>
 * You can find more information on how profiles work with JHipster on <a href="http://jhipster.github.io/profiles/">http://jhipster.github.io/profiles/</a>.
 */
@PostConstruct
public void initApplication() {
    if (env.getActiveProfiles().length == 0) {
        log.warn("No Spring profile configured, running with default configuration");
    } else {
        log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
        Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
        if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION)) {
            log.error("You have misconfigured your application! " +
                "It should not run with both the 'dev' and 'prod' profiles at the same time.");
        }
        if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_CLOUD)) {
            log.error("You have misconfigured your application! " +
                "It should not run with both the 'dev' and 'cloud' profiles at the same time.");
             }
        }
    }
}

Here is city repository class: 这是城市存储库类:

package com.logate.adminpanel.repository;

import com.logate.adminpanel.domain.City;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Spring Data JPA repository for the City entity.
 */
public interface CityRepository extends JpaRepository<City,Long> {

}

and here is city service class: 这是城市服务班:

package com.logate.adminpanel.service;

import com.logate.adminpanel.domain.City;
import com.logate.adminpanel.repository.CityRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;

/**
 * Service Implementation for managing City.
 */
@Service
@Transactional
public class CityService {

    private final Logger log = LoggerFactory.getLogger(CityService.class);

    @Inject
    private CityRepository cityRepository;

    /**
     * Save a city.
     *
     * @param city the entity to save
     * @return the persisted entity
     */
    public City save(City city) {
        log.debug("Request to save City : {}", city);
        City result = cityRepository.save(city);

        return result;
}


    @Transactional(readOnly = true)
    public Page<City> findAll(Pageable pageable) {
        log.debug("Request to get all Cities");
        Page<City> result = cityRepository.findAll(pageable);
        return result;
    }

    @Transactional(readOnly = true)
    public City findOne(Long id) {
        log.debug("Request to get City : {}", id);
        City city = cityRepository.findOne(id);
        return city;
    }

    public void delete(Long id) {
        log.debug("Request to delete City : {}", id);
        cityRepository.delete(id);
    }
}  

Stack trace: 堆栈跟踪:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 30.66   sec <<< FAILURE! - in com.logate.adminpanel.web.rest.CityResourceIntTest
firstTest(com.logate.adminpanel.web.rest.CityResourceIntTest)  Time   elapsed: 0.018 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
        at     org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDeleg    ate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
        at     org.springframework.test.context.support.DefaultTestContext.getApplication    Context(DefaultTestContext.java:83)
        at     org.springframework.test.context.support.DependencyInjectionTestExecutionL    istener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
        at     org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
        at      org.springframework.test.context.TestContextManager.prepareTestInstance(Te    stContextManager.java:228)
        at     org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest    (SpringJUnit4ClassRunner.java:230)
        at     org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)

Console error link: https://jpst.it/OJM6 控制台错误链接: https://jpst.it/OJM6 : https://jpst.it/OJM6

Does anyone have an idea? 有人有主意吗? Thank you in advance. 先感谢您。

Your exception is caused by: java.lang.IllegalStateException: Tomcat connector in failed state . 您的异常是由以下原因引起的: java.lang.IllegalStateException: Tomcat connector in failed state Usually it occurs when port used by tomcat is already in use. 通常在tomcat使用的端口已被使用时发生。 Try to change server.port in src/test/resources/config/application.yml file 尝试在src/test/resources/config/application.yml文件中更改server.port

your stackstrace is telling your com.logate.adminpanel.web.rest.CityResourceIntTest test is failing, not your CityRestTest. 您的stackstrace告诉com.logate.adminpanel.web.rest.CityResourceIntTest测试失败,而不是CityRestTest测试失败。

If you want to have your tests be available to gradle test (which is very recommended if you're using CI/CD systems), the class names have to follow a nameconvention, containing "XXXIntTest" or "XXXUnitTest"... 如果你想拥有你的测试提供给gradle test ,类名必须遵循一个nameconvention,含有“XXXIntTest”或“XXXUnitTest”(如果你使用的CI / CD系统,这是非常推荐)...

I would look to your CityResourceIntTest, since the failure is there...and rename your rest test to the proper nameconvention. 我会去找你的CityResourceIntTest,因为那里有故障...然后将其余测试重命名为适当的名称约定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM