Skip to content

Commit

Permalink
update unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
yixuanQicq committed Dec 5, 2023
1 parent 93ab931 commit 824db26
Show file tree
Hide file tree
Showing 9 changed files with 256 additions and 211 deletions.
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ mvn checkstyle:check
### Prescriptions
- #### /prescription
- #### /prescriptions
- `POST`
- Description: Create a new prescription
- Authentication: Required
Expand All @@ -281,10 +281,14 @@ mvn checkstyle:check
- Output
- On Success
- Status Code: `201`
- Message: `Prescription created successfully`
- On Duplicated `prescriptionId`:
- Status Code: `409`
- Message: `Prescription with ID {prescriptionId} already exists`
- JSON with field:
- `prescriptionId` (String)
- `profileId` (String)
- `rx_number` (Integer)
- `rx_provider` (String)
- `rx_name` (String)
- `refills` (Integer)
- `quantity` (Integer)
- #### /prescription/{prescriptionId}
- `GET`
Expand Down
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,17 @@ public PrescriptionController(PrescriptionService prescriptionService) {

@PostMapping
public ResponseEntity<Prescription> createPrescription(
@AuthenticationPrincipal UserPrincipal principal,
@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Prescription prescription
) {
// return prescriptionService.getPrescriptionById(prescription.getPrescriptionId())
// .flatMap(existingPrescription ->
// Mono.just(new ResponseEntity<String>("Prescription with ID " + prescription.getPrescriptionId() + " already exists.", HttpStatus.CONFLICT)))
// .switchIfEmpty(
// prescriptionService.createPrescription(prescription)
// .then(Mono.just(new ResponseEntity<String>("Prescription created successfully", HttpStatus.CREATED)))
// )
// .block();
Mono<Prescription> prescriptionMono = prescriptionService.createPrescription(prescription);
Prescription newPrescription = prescriptionMono.block();
return ResponseEntity.status(HttpStatus.OK).body(newPrescription);
return ResponseEntity.status(HttpStatus.CREATED).body(newPrescription);
}

@GetMapping("/{prescriptionId}")
public ResponseEntity<Prescription> getPrescriptionById(
@AuthenticationPrincipal UserPrincipal principal,
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String prescriptionId
) {
return prescriptionService.getPrescriptionById(prescriptionId)
Expand All @@ -58,7 +50,7 @@ public ResponseEntity<Prescription> getPrescriptionById(
@PutMapping("/{prescriptionId}")
public ResponseEntity<Prescription> updatePrescription(
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String prescriptionId,
@PathVariable String prescriptionId,
@RequestBody Prescription prescription
) {
return prescriptionService.getPrescriptionById(prescriptionId)
Expand Down Expand Up @@ -93,5 +85,5 @@ public ResponseEntity<List<Prescription>> getPrescriptionsByProfileId(
List<Prescription> prescriptionsList = prescriptionsFlux.collectList().block();
return ResponseEntity.status(HttpStatus.OK).body(prescriptionsList);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public ProfileController(ProfileService profileService) {

@PostMapping
public ResponseEntity<Profile> createProfile(
@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Profile profile)
@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Profile profile)
{
Mono<Profile> profileMono = profileService.createProfile(profile);
Profile newProfile = profileMono.block();
Expand All @@ -34,8 +34,8 @@ public ResponseEntity<Profile> createProfile(

@GetMapping("/{profileId}")
public ResponseEntity<Profile> getProfileById(
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String profileId)
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String profileId)
{
Mono<Profile> profileMono = profileService.getProfileById(profileId);
Profile foundProfile = profileMono.block();
Expand All @@ -44,9 +44,9 @@ public ResponseEntity<Profile> getProfileById(

@PutMapping("/{profileId}")
public ResponseEntity<Profile> updateProfile(
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String profileId,
@RequestBody Profile profile)
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String profileId,
@RequestBody Profile profile)
{
// TODO: updated the dates??
return profileService.getProfileById(profileId)
Expand All @@ -61,18 +61,18 @@ public ResponseEntity<Profile> updateProfile(

@DeleteMapping("/{profileId}")
public ResponseEntity<Void> deleteProfile(
@AuthenticationPrincipal UserPrincipal principal,
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String profileId
) {
Mono<Void> profileMono = profileService.deleteProfile(profileId);
var deletedProfile = profileMono.block();
return ResponseEntity.status(HttpStatus.OK).body(deletedProfile);
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(deletedProfile);
}

@GetMapping("/user/{userId}")
public ResponseEntity<List<Profile>> getProfilesByUserId(
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String userId)
@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String userId)
{
Flux<Profile> profilesFlux = profileService.getProfilesByUserId(userId);
List<Profile> profilesList = profilesFlux.collectList().block();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.google.cloud.firestore.annotation.DocumentId;
import com.google.cloud.spring.data.firestore.Document;

import java.util.Objects;

@Document(collectionName = "prescriptions")
public class Prescription {

Expand Down Expand Up @@ -70,4 +72,17 @@ public String getProfileId() {
public void setProfileId(String profile_id) {
this.profileId = profile_id;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Prescription that = (Prescription) o;
return refills == that.refills && quantity == that.quantity && Objects.equals(prescriptionId, that.prescriptionId) && Objects.equals(profileId, that.profileId) && Objects.equals(rx_number, that.rx_number) && Objects.equals(rx_provider, that.rx_provider) && Objects.equals(rx_name, that.rx_name);
}

@Override
public int hashCode() {
return Objects.hash(prescriptionId, profileId, rx_number, rx_provider, rx_name, refills, quantity);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.google.cloud.spring.data.firestore.Document;

import java.util.List;
import java.util.Objects;

@Document(collectionName = "profiles")
public class Profile {
Expand Down Expand Up @@ -127,4 +128,16 @@ public void setTreatment(String treatment) {

}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Profile profile = (Profile) o;
return age == profile.age && Objects.equals(profileId, profile.profileId) && Objects.equals(userId, profile.userId) && Objects.equals(sex, profile.sex) && Objects.equals(location, profile.location) && Objects.equals(physicalFitness, profile.physicalFitness) && Objects.equals(languagePreference, profile.languagePreference) && Objects.equals(medicalHistory, profile.medicalHistory);
}

@Override
public int hashCode() {
return Objects.hash(profileId, userId, age, sex, location, physicalFitness, languagePreference, medicalHistory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,147 +7,132 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.Date;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.mockito.Mockito.*;

public class ConsentControllerTest {


@InjectMocks
private ConsentController consentController;

@Mock
private ConsentService consentService;
private WebTestClient webTestClient;

private MockMvc mockMvc;
private ObjectMapper objectMapper = new ObjectMapper();

@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
webTestClient = WebTestClient.bindToController(consentController).build();
mockMvc = MockMvcBuilders.standaloneSetup(consentController).build();
}

@Test
void testCreateConsentSuccess() {
// create a new consent
@WithMockUser
void testCreateConsentSuccess() throws Exception {
Date date = new Date();
Consent mockConsent = new Consent("123", "User1", "A2", true, date);
when(consentService.getConsentById("123")).thenReturn(Mono.empty());
when(consentService.createConsent(any(Consent.class))).thenReturn(Mono.just(mockConsent));

webTestClient.post()
.uri("/consents")
.bodyValue(mockConsent)
.exchange()
.expectStatus().isCreated()
.expectBody(String.class)
.isEqualTo("Consent created successfully with ID 123");
mockMvc.perform(post("/consents")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(mockConsent)))
.andExpect(status().isCreated())
.andExpect(content().string("Consent created successfully with ID 123"));
}

@Test
void testCreateConflict() {
// create a new consent
@WithMockUser
void testCreateConflict() throws Exception {
Date date = new Date();
Consent mockConsent = new Consent("123", "User1", "A2", true, date);
when(consentService.getConsentById("123")).thenReturn(Mono.just(mockConsent));
when(consentService.createConsent(any(Consent.class))).thenReturn(Mono.just(mockConsent));

webTestClient.post()
.uri("/consents")
.bodyValue(mockConsent)
.exchange()
.expectStatus().isEqualTo(HttpStatus.CONFLICT)
.expectBody(String.class)
.isEqualTo("Consent with ID 123 already exists.");
try {
mockMvc.perform(post("/consents")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(mockConsent)))
.andExpect(status().isConflict())
.andExpect(content().string("Consent with ID 123 already exists."));
} catch (Exception e) {
fail("Exception thrown during test: " + e.getMessage());
}
}

@Test
void testGetByConsentIdExists(){
// create a new consent
void testGetByConsentIdExists() throws Exception {
Date date = new Date();
Consent mockConsent = new Consent("123", "User1", "A2", true, date);
when(consentService.getConsentById("123")).thenReturn(Mono.just(mockConsent));

webTestClient.get()
.uri("/consents/123")
.exchange()
.expectStatus().isOk()
.expectBody(Consent.class)
.consumeWith(response -> {
assertEquals(mockConsent.getConsentId(), Objects.requireNonNull(response.getResponseBody()).getConsentId());
});
mockMvc.perform(get("/consents/123"))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(mockConsent)));
}

@Test
void testGetConsentByIdDoesNotExist() {
void testGetConsentByIdDoesNotExist() throws Exception {
when(consentService.getConsentById("123")).thenReturn(Mono.empty());

webTestClient.get()
.uri("/consents/123")
.exchange()
.expectStatus().isNotFound();
mockMvc.perform(get("/consents/123"))
.andExpect(status().isNotFound());
}

@Test
void testUpdateConsentExists(){
// create a new consent
void testUpdateConsentExists() throws Exception {
Date date = new Date();
Consent mockConsent = new Consent("123", "User1", "A2", true, date);
when(consentService.getConsentById("123")).thenReturn(Mono.just(mockConsent));
when(consentService.updateConsent(any(Consent.class))).thenReturn(Mono.just(mockConsent));

webTestClient.put()
.uri("/consents/123")
.bodyValue(mockConsent)
.exchange()
.expectStatus().isOk()
.expectBody(Consent.class)
.consumeWith(response -> {
assertEquals(mockConsent.getConsentId(), Objects.requireNonNull(response.getResponseBody()).getConsentId());
});
mockMvc.perform(put("/consents/123")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(mockConsent)))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(mockConsent)));
}

@Test
void testUpdateConsentDoesNotExist() {
void testUpdateConsentDoesNotExist() throws Exception {
when(consentService.getConsentById("123")).thenReturn(Mono.empty());

webTestClient.put()
.uri("/consents/123")
.bodyValue(new Consent())
.exchange()
.expectStatus().isNotFound();
mockMvc.perform(put("/consents/123")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(new Consent())))
.andExpect(status().isNotFound());
}

@Test
void testDeleteConsentExists() {
// create a new consent
void testDeleteConsentExists() throws Exception {
Date date = new Date();
Consent consent = new Consent("123", "User1", "A2", true, date);

// when getConsentById & deleteConsent called, return the same consent
when(consentService.getConsentById("123")).thenReturn(Mono.just(consent));
when(consentService.deleteConsent("123")).thenReturn(Mono.empty());

webTestClient.delete()
.uri("/consents/123")
.exchange()
.expectStatus().isNoContent();
mockMvc.perform(delete("/consents/123"))
.andExpect(status().isNoContent());
}

@Test
void testDeleteConsentDoesNotExist() {
void testDeleteConsentDoesNotExist() throws Exception {
when(consentService.getConsentById("123")).thenReturn(Mono.empty());

webTestClient.delete()
.uri("/consents/123")
.exchange()
.expectStatus().isNotFound();
mockMvc.perform(delete("/consents/123"))
.andExpect(status().isNotFound());
}

}
Loading

0 comments on commit 824db26

Please sign in to comment.