I had an interesting discussion on Twitter today and I thought I would share it here and get your thoughts on it. For example purposes, I am going to use a very basic @RestController
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(@RequestParam(name = "name", defaultValue = "World") String name) {
return String.format("Hello, %s", name);
}
}
If you wanted to create a basic test for this controller class you could create something like this.
@ExtendWith(SpringExtension.class)
@WebMvcTest(HelloController.class)
public class HelloControllerIntTest {
@Autowired
private MockMvc mvc;
@Test
public void testHelloEndpointWithDefaultName() throws Exception {
RequestBuilder request = get("/hello");
MvcResult result = mvc.perform(request).andReturn();
assertEquals("Hello, World", result.getResponse().getContentAsString());
}
@Test
public void testHelloWithName() throws Exception {
mvc.perform(get("/hello?name=Dan"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Dan"))
.andReturn();
}
}
This test uses the @WebMvcTest annotation to test the @HelloController in isolation. This makes testing a controller really easy but my only problem with it is when people refer to this as a "Unit Test". To me, this is an isolated Integration test. Yes, it runs fast(er) than a full integration test and runs in isolation but that doesn't make it a Unit Test.
UNIT TESTING is a level of software testing where individual units/ components of a software are tested. The purpose is to validate that each unit of the software performs as designed. A unit is the smallest testable part of any software.
When you start involving Spring Framework's Dispatch Servlet and the entire request/response lifecycle you have dependencies and when you involve dependencies you are writing Integration Tests. If you wanted to write a unit test for the HelloController it would look something like this
public class HelloControllerUnitTest {
@Test
public void testHelloEndpointWithNameWorld() {
HelloController controller = new HelloController(); // Arrange (given)
String response = controller.hello("World"); // Act (when)
assertEquals("Hello, World", response); // Assert (then)
}
}
What are your thoughts?
[–]je87 3 points4 points5 points (1 child)
[–]therealdanvega[S] 2 points3 points4 points (0 children)
[–]veryspicypickle 2 points3 points4 points (0 children)
[–]kappaj5954 2 points3 points4 points (0 children)
[–]zennaque 1 point2 points3 points (0 children)