I am getting ready to take my Spring Certification v5.0 and there appears to be a question: Do you use Spring in a unit test? Link to Exam Guide questions.
From Spring reference guide I know this:
The POJOs that make up your application should be testable in JUnit or TestNG tests, with objects simply instantiated using the new operator, without Spring or any other container.
From my study as well I can tell that we only are using Spring when testing controllers (like below), repositories or when creating integration tests and maybe some other cases. We would need the TestContext in these cases which is part of org.springframework.* package.
@RunWith(SpringRunner.class)
@WebMvcTest(HelloWorldController.class)
So, is the correct answer of this question: No we do not use Spring? or that, Yes we do need it. Because we obviously use it in some cases.
Advertisement
Answer
The first paragraph you mentioned is the answer to your question, you don’t need Spring to write unit tests for the classes you wrote, even when they’re Spring beans.
The other cases you mentioned aren’t really unit tests. When testing a repository using SpringRunner
and a mock database, you’re no longer writing a unit test, but an integration test. The same applies to writing tests for your controller using MockMvc
. In both cases you’re testing the integration between the Spring framework (Spring MVC or Spring Data) with your code (and a database).
However, you can write unit tests for your controller, but in that case, you would rather do something like this:
@Controller public class HelloWorldController { @RequestMapping("/hello") public ModelAndView getHello() { return new ModelAndView("hello", "title", "hello world"); } } public class HelloWorldControllerTest { private HelloWorldController controller; @Before public void setUp() { controller = new HelloWorldController(); } @Test public void getHelloShouldUseHelloView() { assertThat(controller.getHello().getViewName()).isEqualTo("hello"); } @Test public void getHelloShouldAddATitleModel() { assertThat(controller.getHello().getModel()).containsEntry("title", "Hello world"); } }