2012-11-09 26 views
1

我在測試Spring Junit測試配置時遇到NullPointerException。問題是使用@ContextConfiguration和@Autowired註釋。Spring Test類中的NullPointerException

當我實例化上下文並直接獲取對bean的引用時,如測試方法中註釋掉的代碼所示,測試運行正常併成功。但是,當我嘗試使用@ContextConfiguration和@autowired註釋,並使用相同的XML文件屬性時,我的assertEquals語句中出現NullPointerException。你有什麼想法我做錯了嗎?

package com.greathouse.helloworld.HelloWorldTest; 

import javax.inject.Inject; 

import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
import junit.framework.TestCase; 

@ContextConfiguration(locations = {"classpath:/resources/application-config.xml"}) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class AppTest extends TestCase 
{ 
    @Autowired 
    MessageService messageService; 

    @Test 
    public void testApp() 
    { 
     //ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/resources/application-config.xml"); 
     //messageService = context.getBean("printMessage", MessageService.class); 
     assertEquals(messageService.getMessage(), "Hello World"); 
    } 
} 

回答

7

它看起來像messageService沒有自動裝配。如果您根據需要放置messageService,將會有所幫助。

@Autowired(required = true) 

這種方式當春天的上下文開始春天會告訴你爲什麼它沒有自動裝配你的組件。 另外,作爲一個附註,由於您使用的是JUnit 4,因此您的測試不需要從TestCase擴展。

+0

謝謝,修復它。現在我想知道爲什麼Core Spring文檔沒有說明required = true屬性是必需的。也謝謝你澄清TestCase的擴展,Maven爲我做了這個。但很高興知道什麼是需要的,什麼是多餘的。 – cyotee

+0

屬性require = true不是必需的,但在確定必須解析依賴關係時使用它是很好的。 –

+1

我以爲它默認設置爲required = true? –

0

您的字段messageService未初始化 - 您應該再次取消註釋context.getBean-line。

+0

這不會達到我想要的。 @Autowired註釋執行初始化。它聲明容器使用與該類型匹配的聲明bean來初始化該對象。 – cyotee

相關問題