Mockito

What is Mockito?

Using Mockito with the PersonController class

Person

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    String firstName;
    String lastName;

    public Person() {

    }

    public Person(Long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public boolean equals(Object obj) {
        return this.toString().equals(Objects.requireNonNull(obj).toString());
    }

    @Override
    public String toString() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            return "Person{" +
                    "id=" + id +
                    ", firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    '}';
        }
    }
}

PersonService


@Service
public class PersonService {
    private PersonRepository repository;

    @Autowired
    public PersonService(PersonRepository repository) {
        this.repository = repository;
    }

    public Person create(Person person) {
        Person personCreated = repository.save(person);
        return personCreated;
    }

    public Person read(Long id) {
        Optional<Person> potentialPerson = repository.findById(id);
        Person person = potentialPerson.get();
        return person;
    }

    public Person update(Long id, Person person) {
        Person personInDataBase = read(id);
        String newFirstName = person.getFirstName();
        String newLastName = person.getLastName();

        personInDataBase.setFirstName(newFirstName);
        personInDataBase.setLastName(newLastName);
        repository.save(personInDataBase);
        return personInDataBase;
    }

    public Person delete(Long id) {
        Person person = read(id);
        repository.delete(person);
        return person;
    }

    public List<Person> readAll() {
        List<Person> personList = new ArrayList<>();
        repository.findAll().forEach(personList::add);
        return personList;
    }
}

PersonController


@CrossOrigin(origins = "*")
@RequestMapping(value = "/person-controller")
@RestController
public class PersonController {
    private PersonService service;

    @Autowired
    public PersonController(PersonService service) {
        this.service = service;
    }


    @RequestMapping(path = "/create", method = RequestMethod.POST)
    public ResponseEntity<Person> create(@RequestBody Person person) {
        Person responseBody = service.create(person);
        ResponseEntity responseEntity = new ResponseEntity<>(responseBody, HttpStatus.OK);
        return responseEntity;
    }


    @RequestMapping(value = "/read", method = RequestMethod.GET)
    public ResponseEntity<Person> read(@PathVariable Long id) {
        Person responseBody = service.read(id);
        ResponseEntity responseEntity = new ResponseEntity<>(responseBody, HttpStatus.OK);
        return responseEntity;
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public ResponseEntity<Person> update(@PathVariable Long id, @RequestBody Person person) {
        Person responseBody = service.update(id, person);
        ResponseEntity responseEntity = new ResponseEntity<>(responseBody, HttpStatus.OK);
        return responseEntity;
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Person> delete(@PathVariable Long id) {
        Person responseBody = service.delete(id);
        ResponseEntity responseEntity = new ResponseEntity<>(responseBody, HttpStatus.OK);
        return responseEntity;
    }


    @RequestMapping(value = "/read-all", method = RequestMethod.GET)
    public ResponseEntity<List<Person>> readAll() {
        List<Person> responseBody = service.readAll();
        ResponseEntity responseEntity = new ResponseEntity<>(responseBody, HttpStatus.OK);
        return responseEntity;
    }
}

Using Mockito with the PersonController and Person classes

@Test
public void testCreate() {
    // Given: Create mock PersonService
    PersonService service = mock(PersonService.class);
    PersonController controller = new PersonController(mockService);
    Person expected = new Person(1L, "John", "Doe");
    // Given: Stub create method to return predetermined Person object
    when(mockService.create(any(Person.class))).thenReturn(expected);
    // Given: Instantiate PersonController using mock PersonService

    // When: Invoke create method on PersonController
    ResponseEntity<Person> response = controller.create(new Person());

    // Then: Assert that response contains expected Person object and HTTP status code
    assertEquals(expected, response.getBody());
    assertEquals(HttpStatus.OK, response.getStatusCode());
}