@Autowired 字段在测试中始终为空,我错过了什么?

测试性能:


package com.sandbox.test;


import lombok.Getter;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;


@Component

@PropertySource("classpath:new-test.properties")

public class TestProperties {

    @Getter

    @Value("${homepage.url}")

    private String homePageUrl;

}

配置:


package com.sandbox.test;


import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;


@Configuration

@ComponentScan(basePackages = {"com.sandbox"})

public class SpringContext {

}

new-test.properties位于 /src/test/resources 中的文件内容:


homepage.url=https://tst.mysite.com

课堂上进行了两次测试MyTest,第一个 - 不起作用,第二个 - 工作正常:


package com.sandbox.test;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import org.springframework.test.context.ContextConfiguration;

import org.testng.Assert;

import org.testng.annotations.Test;


@ContextConfiguration(classes = {SpringContext.class})

public class MyTest {


    @Autowired

    private TestProperties testProperties;


    @Test

    public void thisDoesntWork() {

        Assert.assertNotNull(testProperties);

        System.out.println(testProperties.getHomePageUrl());

    }


    @Test

    public void thisWorks() {

        AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(SpringContext.class);

        TestProperties testProps = appContext.getBean(TestProperties.class);


        Assert.assertNotNull(testProps);

        System.out.println(testProps.getHomePageUrl());

    }

}

目标是在不使用 xml 的情况下自动装配类testProperties中的字段。但目前是. 注释已经到位,但我缺少什么?...MyTestnull@Component@ComponentScan


海绵宝宝撒
浏览 49回答 1
1回答

吃鸡游戏

您的测试可能需要扩展 AbstractTestNGSpringContextTests才能自动访问ApplicationContext并使自动装配工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java