Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: improve test assertions #1473

Merged
merged 12 commits into from
May 16, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ void shouldNotValidateWhenFirstNameEmpty() {

assertThat(constraintViolations).hasSize(1);
ConstraintViolation<Person> violation = constraintViolations.iterator().next();
assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
assertThat(violation.getPropertyPath()).hasToString("firstName");
assertThat(violation.getMessage()).isEqualTo("must not be blank");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,7 @@

package org.springframework.samples.petclinic.owner;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

import java.time.LocalDate;
import java.util.List;

import org.assertj.core.util.Lists;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledInNativeImage;
Expand All @@ -49,6 +30,25 @@
import org.springframework.test.context.aot.DisabledInAotMode;
import org.springframework.test.web.servlet.MockMvc;

import java.time.LocalDate;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

/**
* Test class for {@link OwnerController}
*
Expand Down Expand Up @@ -84,16 +84,16 @@ private Owner george() {
george.addPet(max);
max.setId(1);
return george;
};
}

@BeforeEach
void setup() {

Owner george = george();
given(this.owners.findByLastName(eq("Franklin"), any(Pageable.class)))
.willReturn(new PageImpl<Owner>(Lists.newArrayList(george)));
.willReturn(new PageImpl<>(Lists.newArrayList(george)));

given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl<Owner>(Lists.newArrayList(george)));
given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl<>(Lists.newArrayList(george)));

given(this.owners.findById(TEST_OWNER_ID)).willReturn(george);
Visit visit = new Visit();
Expand Down Expand Up @@ -142,14 +142,14 @@ void testInitFindForm() throws Exception {

@Test
void testProcessFindFormSuccess() throws Exception {
Page<Owner> tasks = new PageImpl<Owner>(Lists.newArrayList(george(), new Owner()));
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList(george(), new Owner()));
Mockito.when(this.owners.findByLastName(anyString(), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1")).andExpect(status().isOk()).andExpect(view().name("owners/ownersList"));
}

@Test
void testProcessFindFormByLastName() throws Exception {
Page<Owner> tasks = new PageImpl<Owner>(Lists.newArrayList(george()));
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList(george()));
Mockito.when(this.owners.findByLastName(eq("Franklin"), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", "Franklin"))
.andExpect(status().is3xxRedirection())
Expand All @@ -158,7 +158,7 @@ void testProcessFindFormByLastName() throws Exception {

@Test
void testProcessFindFormNoOwnersFound() throws Exception {
Page<Owner> tasks = new PageImpl<Owner>(Lists.newArrayList());
Page<Owner> tasks = new PageImpl<>(Lists.newArrayList());
Mockito.when(this.owners.findByLastName(eq("Unknown Surname"), any(Pageable.class))).thenReturn(tasks);
mockMvc.perform(get("/owners?page=1").param("lastName", "Unknown Surname"))
.andExpect(status().isOk())
Expand Down Expand Up @@ -224,24 +224,7 @@ void testShowOwner() throws Exception {
.andExpect(model().attribute("owner", hasProperty("city", is("Madison"))))
.andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023"))))
.andExpect(model().attribute("owner", hasProperty("pets", not(empty()))))
.andExpect(model().attribute("owner", hasProperty("pets", new BaseMatcher<List<Pet>>() {

@Override
public boolean matches(Object item) {
@SuppressWarnings("unchecked")
List<Pet> pets = (List<Pet>) item;
Pet pet = pets.get(0);
if (pet.getVisits().isEmpty()) {
anyulled marked this conversation as resolved.
Show resolved Hide resolved
return false;
}
return true;
}

@Override
public void describeTo(Description description) {
description.appendText("Max did not have any visits");
}
})))
.andExpect(model().attribute("owner", hasProperty("pets", hasItem(hasProperty("visits", hasSize(greaterThan(0)))))))
.andExpect(view().name("owners/ownerDetails"));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ void shouldInsertOwner() {
owner.setCity("Wollongong");
owner.setTelephone("4444444444");
this.owners.save(owner);
assertThat(owner.getId().longValue()).isNotEqualTo(0);
assertThat(owner.getId()).isNotZero();

owners = this.owners.findByLastName("Schultz", pageable);
assertThat(owners.getTotalElements()).isEqualTo(found + 1);
Expand Down Expand Up @@ -155,20 +155,20 @@ void shouldInsertPetIntoDatabaseAndGenerateId() {
pet.setType(EntityUtils.getById(types, PetType.class, 2));
pet.setBirthDate(LocalDate.now());
owner6.addPet(pet);
assertThat(owner6.getPets().size()).isEqualTo(found + 1);
assertThat(owner6.getPets()).hasSize(found + 1);

this.owners.save(owner6);

owner6 = this.owners.findById(6);
assertThat(owner6.getPets().size()).isEqualTo(found + 1);
assertThat(owner6.getPets()).hasSize(found + 1);
// checks that id has been generated
pet = owner6.getPet("bowser");
assertThat(pet.getId()).isNotNull();
}

@Test
@Transactional
void shouldUpdatePetName() throws Exception {
void shouldUpdatePetName() {
Owner owner6 = this.owners.findById(6);
Pet pet7 = owner6.getPet(7);
String oldName = pet7.getName();
Expand Down Expand Up @@ -213,7 +213,7 @@ void shouldAddNewVisitForPet() {
}

@Test
void shouldFindVisitsByPetId() throws Exception {
void shouldFindVisitsByPetId() {
Owner owner6 = this.owners.findById(6);
Pet pet7 = owner6.getPet(7);
Collection<Visit> visits = pet7.getVisits();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -68,10 +69,10 @@ void testTriggerExceptionJson() {
new ParameterizedTypeReference<Map<String, Object>>() {
});
assertThat(resp).isNotNull();
assertThat(resp.getStatusCode().is5xxServerError());
assertThat(resp.getBody().containsKey("timestamp"));
assertThat(resp.getBody().containsKey("status"));
assertThat(resp.getBody().containsKey("error"));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(resp.getBody()).containsKey("timestamp");
assertThat(resp.getBody()).containsKey("status");
assertThat(resp.getBody()).containsKey("error");
assertThat(resp.getBody()).containsEntry("message",
"Expected: controller used to showcase what happens when an exception is thrown");
assertThat(resp.getBody()).containsEntry("path", "/oups");
Expand All @@ -84,7 +85,7 @@ void testTriggerExceptionHtml() {
ResponseEntity<String> resp = rest.exchange("http://localhost:" + port + "/oups", HttpMethod.GET,
new HttpEntity<>(headers), String.class);
assertThat(resp).isNotNull();
assertThat(resp.getStatusCode().is5xxServerError());
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(resp.getBody()).isNotNull();
// html:
assertThat(resp.getBody()).containsSubsequence("<body>", "<h2>", "Something happened...", "</h2>", "<p>",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@

package org.springframework.samples.petclinic.system;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
* Test class for {@link CrashController}
*
Expand All @@ -34,13 +33,10 @@ class CrashControllerTests {
CrashController testee = new CrashController();

@Test
void testTriggerException() throws Exception {
RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
testee.triggerException();
});

assertEquals("Expected: controller used to showcase what happens when an exception is thrown",
thrown.getMessage());
void testTriggerException() {
anyulled marked this conversation as resolved.
Show resolved Hide resolved
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(()->testee.triggerException())
.withMessageContaining("Expected: controller used to showcase what happens when an exception is thrown");
}

}