写Junit测试时用Autowired注入的类实例始终为空怎么解?

踩坑半天多,终于在网上寻觅到了解决方案,特此分享一下。

重要前提:src/main/java下的根包名必须和src/test/main的根包名完全一致,否则就会发生死活不能注入的情况,要继续进行下面的步骤,请先确认这个重要前提。

再接下来就是常规配置了。

pom.xml增加依赖spring-boot-starter-test,它会引入JUnit的测试包:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

然后给需要注入的类增加Component或是Service注解:

@SpringBootApplication
@Component
public class WebhookApplication implements CommandLineRunner {
    private final Logger logger = LoggerFactory.getLogger(WebhookApplication.class);

    // Proxy server(from application-dev(stg,prod,qa).yml)
    @Value("${webhook.proxy}")
    private String proxy;

    public void setProxy(String proxy) {
        this.proxy = proxy;
    }
...
}
@Service
public class WebhookService {
    private final Logger logger = LoggerFactory.getLogger(WebhookService.class);
    ...
}

写Component或是Service注解目的是能让这些类可以被Autowired方式输入。

再往下就是写测试类了:

@RunWith(SpringRunner.class)  
@SpringBootTest
public class WebhookApplicationTest {
    @Autowired
    private WebhookApplication app=null;
    
    @Autowired
    private WebhookService service=null;
    
    @Test
    public void test() {
        Assert.assertNotNull(app);
    }
    
    @Test
    public void test2() {
        Assert.assertNotNull(service);
    }
...
}

其中SpringRunner是Spring结合JUnit的运行器,说明这里可以进行JUnit测试。

注解@SpringBootTest是可以配置SpringBoot的关于测试的相关功能。

完事以后,运行test或是test2,能发现app或是service不为空了,这说明注入正确了。

--2020-04-09--

参考资料一:https://blog.csdn.net/it_erge/article/details/86605684?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2

参考资料二:《深入浅出SpringBoot2.x》杨开振著

原文地址:https://www.cnblogs.com/heyang78/p/12664493.html