Created
November 14, 2018 09:23
-
-
Save odidere/7fa68a79447d6b250ad6fd5ae9f30f89 to your computer and use it in GitHub Desktop.
Unit test for a spring controller class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package shina.sample.controller; | |
import java.net.URI; | |
import java.util.List; | |
import shina.sample.dto.PersonDTO; | |
import org.hibernate.ObjectNotFoundException; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.util.MimeTypeUtils; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.PathVariable; | |
import org.springframework.web.bind.annotation.PostMapping; | |
import org.springframework.web.bind.annotation.RequestBody; | |
import org.springframework.web.bind.annotation.RestController; | |
import shina.sample.model.Person; | |
import shina.sample.service.PersonService; | |
import org.springframework.web.servlet.support.ServletUriComponentsBuilder; | |
import javax.validation.Valid; | |
/** | |
* Spring REST controller for processing request on Person objects | |
* @author ShinaSamuel | |
*/ | |
@RestController | |
public class PersonController { | |
private final PersonService personService; | |
/** | |
* Autowired constructor | |
* | |
* @param personService service {@link PersonService} | |
*/ | |
@Autowired | |
public PersonController(PersonService personService){ | |
this.personService = personService; | |
} | |
/** | |
* Registers new {@link Person} | |
* | |
* @param personDTO {@link PersonDTO} | |
* @return object {@link ResponseEntity} with created {@link Person} | |
*/ | |
@PostMapping(path = "/api/person", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) | |
public ResponseEntity<Person> register(@Valid @RequestBody final PersonDTO personDTO) { | |
Person person = personService.save(personDTO); | |
URI uri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/api/person/{person-id}") | |
.buildAndExpand(person.getId()).toUri(); | |
return ResponseEntity.created(uri).body(person); | |
} | |
/** | |
* Gets all objects {@link Person} | |
* | |
* @return object {@link ResponseEntity} with collection of all {@link Person} | |
*/ | |
@GetMapping(path = "/api/person", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) | |
public ResponseEntity<List<Person>> getAllPersons() { | |
return ResponseEntity.ok(personService.getAll()); | |
} | |
/** | |
* Get {@link Person} by id | |
* | |
* @param personId id of required person | |
* | |
* @return object {@link ResponseEntity} with required {@link Person} | |
*/ | |
@GetMapping(path = "/api/person/{person-id}", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) | |
public ResponseEntity<Person> getPersonById(@PathVariable(name="person-id") final Long personId) { | |
Person person = personService.findById(personId); | |
if (person == null) { | |
throw new ObjectNotFoundException(personId,"person-id"); | |
} | |
return ResponseEntity.ok(person); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package shina.sample.controller; | |
import shina.sample.common.TestUtil; | |
import shina.sample.dto.PersonDTO; | |
import shina.sample.model.Person; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import org.junit.Assert; | |
import org.junit.Before; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.mockito.Mock; | |
import org.modelmapper.ModelMapper; | |
import org.springframework.boot.test.context.SpringBootTest; | |
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; | |
import org.springframework.http.HttpStatus; | |
import org.springframework.http.MediaType; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | |
import org.springframework.test.web.servlet.MockMvc; | |
import org.springframework.test.web.servlet.MvcResult; | |
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; | |
import org.springframework.test.web.servlet.setup.MockMvcBuilders; | |
import java.util.Arrays; | |
import java.util.List; | |
import static org.assertj.core.api.Java6Assertions.assertThat; | |
import static org.junit.Assert.assertEquals; | |
import static org.junit.Assert.assertNotNull; | |
import static org.mockito.Mockito.when; | |
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; | |
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | |
/** | |
* @author ShinaSamuel | |
* | |
*/ | |
@RunWith(SpringJUnit4ClassRunner.class) | |
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) | |
public class PersonControllerTest{ | |
private static final String EMAIL = "[email protected]"; | |
private static final String REGISTRATION_NUMBER = "868686868686"; | |
private static final Long PERSON_ID = 1L; | |
private static final Long PERSON_ID2 = 2L; | |
private static final String NAME = "Shina Samuel"; | |
@Mock | |
private PersonController personController; | |
private MockMvc mockMvc; | |
private ModelMapper modelMapper; | |
private ObjectMapper objectMapper; | |
@Before | |
public void setup(){ | |
mockMvc = MockMvcBuilders.standaloneSetup(personController).build(); | |
objectMapper = new ObjectMapper(); | |
modelMapper = new ModelMapper(); | |
} | |
@Test | |
public void controllerInitializedCorrectly() { | |
assertThat(personController).isNotNull(); | |
} | |
@Test | |
public void testPersonShouldBeRegistered() throws Exception { | |
// GIVEN | |
Person person = TestUtil.createPerson(PERSON_ID, NAME, EMAIL, REGISTRATION_NUMBER); | |
PersonDTO personDTO = modelMapper.map(person, PersonDTO.class); | |
ResponseEntity<Person> responseEntity = new ResponseEntity<>(person, HttpStatus.CREATED); | |
when(personController.register(personDTO)).thenReturn(responseEntity); | |
// WHEN | |
MvcResult result = mockMvc.perform(MockMvcRequestBuilders | |
.post("/api/person") | |
.contentType(MediaType.APPLICATION_JSON).content(personString)) | |
.andExpect(status().isCreated()).andReturn(); | |
Person person1 = objectMapper.readValue(result.getResponse().getContentAsByteArray(), Person.class); | |
// THEN | |
Assert.assertEquals(NAME, person1.getName()); | |
} | |
@Test | |
public void testPersonById() throws Exception{ | |
// GIVEN | |
Person person = TestUtil.createPerson(PERSON_ID, NAME, EMAIL, REGISTRATION_NUMBER); | |
ResponseEntity<Person> responseEntity = new ResponseEntity<>(person, HttpStatus.OK); | |
when(personController.getPersonById(1L)).thenReturn(responseEntity); | |
// WHEN | |
MvcResult result = mockMvc.perform(get("/api/person/1")) | |
.andExpect(status().isOk()).andReturn(); | |
Person person2 = objectMapper.readValue(result.getResponse().getContentAsString(), Person.class); | |
// THEN | |
assertEquals(EMAIL, person2.getEmail()); | |
} | |
@Test | |
public void testGetAllPersons() throws Exception { | |
// GIVEN | |
Person person1 = TestUtil.createPerson(PERSON_ID, NAME, EMAIL, REGISTRATION_NUMBER); | |
Person person2 = TestUtil.createPerson(PERSON_ID2, NAME, EMAIL, REGISTRATION_NUMBER); | |
List<Person> mockListPerson = Arrays.asList(person1,person2); | |
ResponseEntity<List<Person>> responseEntity = new ResponseEntity<>(mockListPerson, HttpStatus.OK); | |
when(personController.getAllPersons()).thenReturn(responseEntity); | |
// WHEN | |
MvcResult result = mockMvc.perform(get("/api/person")) | |
.andExpect(status().isOk()).andReturn(); | |
List<Person> persons = objectMapper.readValue(result.getResponse().getContentAsString(), | |
objectMapper.getTypeFactory().constructCollectionType(List.class, Person.class)); | |
Person personResult = persons.stream().filter(p -> p.getEmail().equals(EMAIL)).findFirst().orElse(null); | |
// THEN | |
assertEquals(persons.size(), 2); | |
assertNotNull(personResult); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment