我有以下具有不同配置文件的弹簧测试配置:

@Configuration
@ComponentScan (value = {"uk.co.test.ws" })
public class SpringTestConfig
{


    @Profile( "local")
    @PropertySource( "classpath:/config/local/settings.properties" )
    public static class SpringTestConfigLocal
    {
        @Autowired
        private Environment environment ;

        @Bean(name= "baseUrl" )
        public String setBaseUrl()
        {
            return environment .getRequiredProperty("baseurl.protocol" )+"://" +environment .getRequiredProperty( "baseurl.host");
        }
    }


然后创建一个接受基本网址的基类

> @RunWith (SpringJUnit4ClassRunner. class) @ContextConfiguration
> (classes = { SpringTestConfig. class }) public class BaseWsTest {
>     @Autowired
>     String baseUrl;


然后将其扩展到其他测试类,如下所示:

public class SampleFTest extends BaseWsTest
{
    @Test
    public void hello() throws FileNotFoundException, Exception
    {
        System. out .println("base url: " + baseUrl );


当使用普通的maven clean install运行时,测试有效,但如果我通过右键单击该方法运行它,则会得到一个

Error creating bean with name 'uk.co.test.ws.service.base.SampleFTest': Injection of autowired dependencies failed;

最佳答案

您忘记在SampleFTest类中选择配置文件,应添加以下行:

@ActiveProfiles(profiles = "local")


这样,将初始化SpringTestConfigLocal并提供baseUrl bean

编辑:我会在.properties文件中添加一个属性,以便可以使用变量myprofile:

@ActiveProfiles(profiles = "${myprofile}")

最后,如果您不想不时更改该值,我将应用一些逻辑以便加载一个或另一个属性文件。

编辑2:很抱歉,但是这行不通,因为在注释EL值分配之后加载了文件,但是您可以添加以下代码:

spring.profiles.active=local


到属性文件,这和放置注释@IntegrationTest("local")相同。这是我尝试的代码:

@TestPropertySource(value="classpath:/config/test.properties")//, properties={"myaddress=cane", "myprofile=local"})
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("${myaddress}")
//@ContextConfiguration
//@ActiveProfiles(profiles = "${myprofile}")
public class BasicJUnitTest{

    protected Logger logger;

    protected MockMvc mockMvc;

    @Autowired
    private Environment env;


    @Value("${myaddress}" )
    String myval;


    public BasicJUnitTest(){
        this.logger = LoggerFactory.getLogger(this.getClass());
    }

    @Test
    public void test(){
        logger.info("hola"+myval+ " " + env.getActiveProfiles()[0]);
    }


}

10-08 07:06