Tutorial - test driven development (TDD)
This tutorial shows how to use Diffblue Cover Plugin for IntelliJ with test driven development (TDD).
In this tutorial we will look at how to use Diffblue Cover Plugin for IntelliJ when using test-driven development (TDD) for implementing a new feature.
To follow this part of the tutorial on your own, please do the following steps:
git clone https://github.com/Diffblue-benchmarks/Spring-petclinic
cd Spring-petclinic
git checkout a-test-tdd
- Open the project in IntelliJ.
- Navigate to the
OwnerController
class.
1. We are going to add a new feature to the
OwnerController
class (that is specified as follows): /**
* @GetMapping("/owners") public String processFindForm(Owner owner, ...)
* Look up the owner in the database by the given last name.
* If a single owner is found, redirect to /owners/{ownerId}.
* If several owners are found, allow selection of an owner in owners/ownersList.
*/
TDD requires us to write the tests before implementing the functionality. So, we start by manually implementing tests for this new
processFindForm
method.2. We first have to set up the test class wiring the required beans:
@WebMvcTest(controllers = {OwnerController.class})
@ExtendWith(SpringExtension.class)
public class OwnerControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean(name = "ownerRepository")
private OwnerRepository ownerRepository;
@MockBean(name = "visitRepository")
private VisitRepository visitRepository;
...
3. We then add a test method for the case where a single owner is found and we redirect to that owner:
…
@Test
public void testProcessFindForm_singleOwner() throws Exception {
Owner owner = new Owner();
owner.setLastName("Doe");
owner.setId(1);
owner.setCity("Oxford");
owner.setAddress("42 Main St");
owner.setFirstName("Jane");
owner.setTelephone("4105551212");
when(this.ownerRepository.findByLastName(or(isA(String.class), isNull())))
.thenReturn(Collections.singletonList(owner));
this.mockMvc.perform(get("/owners").param("lastName", "Doe"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/1"));
}
…
4. We then write a test for the case where multiple owners are found and we display the list for selecting an owner:
…
@Test
public void testProcessFindForm_severalOwners() throws Exception {
Owner owner1 = new Owner();
owner1.setLastName("Doe");
owner1.setId(1);
owner1.setCity("Oxford");
owner1.setAddress("42 Main St");
owner1.setFirstName("Jane");
owner1.setTelephone("4105551212");
Owner owner2 = new Owner();
owner2.setLastName("Doe");
owner2.setId(1);
owner2.setCity("Oxford");
owner2.setAddress("1 High St");
owner2.setFirstName("John");
owner2.setTelephone("5121241055");