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
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.
@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.
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.
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.
Create a bean of type MockHttpServletRequest
and add it to your test context. This should then be autowired into your target bean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With