我在測試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");
}
}
謝謝,修復它。現在我想知道爲什麼Core Spring文檔沒有說明required = true屬性是必需的。也謝謝你澄清TestCase的擴展,Maven爲我做了這個。但很高興知道什麼是需要的,什麼是多餘的。 – cyotee
屬性require = true不是必需的,但在確定必須解析依賴關係時使用它是很好的。 –
我以爲它默認設置爲required = true? –