Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I've injected HttpServletRequest into a bean. How do I unit test it?

Tags:

junit

spring

I have a bean in which I've injected an HttpServletRequest using the @Autowired annotation.

This injection works correctly when the application context is a web application Context. That's not the case for application contexts for JUnit tests with Spring.

How can I test this bean ? Maybe I can mock an http request, but then how to inject this mock in the bean ?

This is on Spring 3.0 and Junit 4.4

like image 823
Leonel Avatar asked Aug 26 '10 17:08

Leonel


People also ask

How to get HttpServletRequest in JUnit?

4. JUnit HttpServletRequest Example. First of all, we will create a new servlet. To create that, we simply right click on project name -> New -> Other -> Servlet under Web.

What is SpringJUnitConfig?

@SpringJUnitConfig is a composed annotation that combines @ExtendWith(SpringExtension. class) from JUnit Jupiter with @ContextConfiguration from the Spring TestContext Framework. As of Spring Framework 5.3, this annotation will effectively be inherited from an enclosing test class by default.

Is HttpServletRequest a singleton?

In any Java servlet container, such as Apache Tomcat, HttpServlet is a singleton class (see MSC07-J. Prevent multiple instantiations of singleton objects for information related to singleton classes). Therefore, there can be only one instance of member variables, even if they are not declared static.

Which class is used to test Spring MVC rest Web application?

We create the test data by using a test data builder class. Configure our mock object to return the created test data when its findAll() method is invoked.


1 Answers

Create a bean of type MockHttpServletRequest and add it to your test context. This should then be autowired into your target bean.

like image 75
skaffman Avatar answered Sep 22 '22 10:09

skaffman