寫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》楊開振著


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM