2011-09-19 14 views
11

Web uygulamam için testler yapmak isterim, ancak içerik yapılandırması servletContext otomasyonunda çöküyor. Altında hata var. Tomcat/jetty üzerinde web uygulamasını çalıştırdığımda otomatik iletim servletContext iyi çalışıyor.Birim testi Spring MVC web uygulaması: Otomatik alan yapılamadı: private javax.servlet.ServletContext

java.lang.IllegalStateException: org.springframework.beans.factory.BeanCreationException: Neden Olduğu ApplicationContext ... yüklenemedi Hata adı 'testController' ile fasulye oluşturma: autowired bağımlılıkları Enjeksiyonu başarısız; iç içe istisna org.springframework.beans.factory.BeanCreationException: otowire alanı olamaz: özel javax.servlet.ServletContext com.test.controllers.TestController.servletContext; İç içe istisna org.springframework.beans.factory.NoSuchBeanDefinitionException şudur: Bu bağımlılık için autowire adayı olarak nitelendirir beklenen en az 1 fasulyesi: tipteki bir eşleşen fasulye [javax.servlet.ServletContext] bağımlılık bulundu. Bağımlılık açıklamalar:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration("classpath:applicationContext.xml") 
public class FirstTest { 

    @Test 
    public void doTest() throws Exception { 
     // ... 
    } 
} 

TestController

@Controller 
public class TestController { 

    @Autowired 
    private ServletContext servletContext; 

    ... 
} 
+1

bu ilgili yanıta bakın kayboldu http://stackoverflow.com/questions/2674697/how-to-inject-servletcontext-for-junit -test- – ptomli

+0

teşekkürler. 'ContextConfiguration' ile' MockServletContext' nasıl kullanılır? – marioosh

+0

Sadece 'MockServletContext' için' applicationContext.xml' dosyanızdaki tanımını – ptomli

cevap

24

ptomli ipucu göre, MockServletContext fasulye tanımlama yapmak {org.springframework.beans.factory.annotation.Autowired @ (= doğru gerekli)} hile.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException 

Soultion: applicationContext.xml gelen konfigürasyon dosyasında ayrı fayans ve jUnit testlerinde fayans kullanmayın çıktı

<bean class="org.springframework.mock.web.MockServletContext"/> 

başka sorun, çalışmadığını, tilesConfigurer oldu.

<?xml version="1.0" encoding="UTF-8"?> 
<web-app> 
    <context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value> 
      classpath:applicationContext.xml 
      classpath:tilesConfig.xml 
     </param-value> 
    </context-param> 
</web-app> 
+4

Çalışır. Başka bir seçenek @WebAppConfiguration – borjab

10

Ben deney sınıfı altında @WebAppConfiguration eklemiş ve problem

+0

ile testi iptal etmektir. Ve bu doğru cevap olduğunu varsayalım. –