2011-09-19 24 views
11

Tôi muốn thực hiện các kiểm tra cho ứng dụng web của mình, nhưng cấu hình ngữ cảnh bị treo trên autowiring servletContext. Lỗi dưới đây. Autowiring servletContext hoạt động tốt khi tôi chạy ứng dụng web trên tomcat/jetty.Thử nghiệm đơn vị Ứng dụng web Spring MVC: Không thể tự động điền trường: private javax.servlet.ServletContext

java.lang.IllegalStateException: Không thể tải ApplicationContext ... Nguyên nhân: org.springframework.beans.factory.BeanCreationException: Lỗi tạo đậu với tên 'testController': Tiêm autowired phụ thuộc thất bại; ngoại lệ lồng nhau là org.springframework.beans.factory.BeanCreationException: Không thể trường autowire: private javax.servlet.ServletContext com.test.controllers.TestController.servletContext; lồng nhau ngoại lệ là org.springframework.beans.factory.NoSuchBeanDefinitionException: Không đậu kết hợp của loại [javax.servlet.ServletContext] tìm thấy cho phụ thuộc: dự kiến ​​ít nhất 1 đậu mà đủ điều kiện như autowire ứng cử viên cho sự phụ thuộc này. Phụ thuộc chú thích: {@ org.springframework.beans.factory.annotation.Autowired (bắt buộc = true)}

@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

Xem câu trả lời liên quan này http://stackoverflow.com/questions/2674697/how-to-inject-servletcontext-for-junit -tests-with-spring – ptomli

+0

Cảm ơn. Làm thế nào để sử dụng 'MockServletContext' với' @ ContextConfiguration'? – marioosh

+0

Chỉ cần bao gồm định nghĩa cho 'MockServletContext' trong tệp' applicationContext.xml' – ptomli

Trả lời

24

Theo ptomli gợi ý định MockServletContext đậu làm lừa.

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

Một vấn đề khác, trong đó xuất hiện là tilesConfigurer, điều đó không làm việc:

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: gạch riêng biệt cấu hình từ applicationContext.xml và không sử dụng gạch trong các thử nghiệm JUnit.

<?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

Nó hoạt động. Một tùy chọn khác là để anotate thử nghiệm với @WebAppConfiguration – borjab

10

Tôi đã thêm @WebAppConfiguration dưới lớp thử nghiệm và vấn đề biến mất

+0

Và tôi cho rằng đây là câu trả lời đúng. –

Các vấn đề liên quan