Skip to content

Commit 9f48ff0

Browse files
authored
fix: increase oracle api project test coverage (#2002)
1 parent 105659e commit 9f48ff0

File tree

8 files changed

+960
-20
lines changed

8 files changed

+960
-20
lines changed

oracle-api/pom.xml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,9 +269,11 @@
269269
<skip>${jacoco.skip}</skip>
270270
<excludes>
271271
<exclude>**/config/**</exclude>
272-
<exclude>**/filter/**</exclude>
273-
<exclude>**/interceptor/**</exclude>
272+
<exclude>**/filter/**</exclude>
273+
<exclude>**/interceptor/**</exclude>
274274
<exclude>**/*$*Builder*</exclude>
275+
<exclude>**/entity/**</exclude>
276+
<exclude>**/dto/**</exclude>
275277
<exclude>**/BackendStartApiApplication.*</exclude>
276278
</excludes>
277279
</configuration>

oracle-api/src/main/java/ca/bc/gov/oracleapi/endpoint/consep/MoistureContentConesEndpoint.java

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ public List<Integer> deleteReplicates(
401401
/**
402402
* Calculate the average of a list of numbers.
403403
*
404-
* @param numbers A list of numbers to calculate the average.
404+
* @param mcValueArray A list of numbers to calculate the average.
405405
* @return The calculated average.
406406
*/
407407
@PostMapping(value = "/{riaKey}/calculate-average", produces = "application/json")
@@ -422,22 +422,30 @@ public ResponseEntity<Double> calculateAverage(
422422
@PathVariable
423423
BigDecimal riaKey,
424424
@RequestBody List<Double> mcValueArray) {
425-
try {
426-
// Validate input
427-
if (mcValueArray == null || mcValueArray.isEmpty()) {
428-
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "MC Value Array cannot be null or empty.");
429-
}
430-
double average = moistureContentService.calculateAverage(riaKey, mcValueArray);
431-
return ResponseEntity.status(HttpStatus.OK).body(average);
432-
} catch (IllegalArgumentException e) {
433-
// Handle specific exceptions (e.g., invalid arguments)
434-
SparLog.error("Invalid input for calculateAverage: {}", e.getMessage(), e);
435-
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid input: " + e.getMessage(), e);
436-
437-
} catch (Exception e) {
438-
// Handle unexpected exceptions
439-
SparLog.error("Unexpected error in calculateAverage: {}", e.getMessage(), e);
440-
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred: " + e.getMessage(), e);
425+
try {
426+
if (mcValueArray == null || mcValueArray.isEmpty()) {
427+
throw new ResponseStatusException(
428+
HttpStatus.BAD_REQUEST,
429+
"MC Value Array cannot be null or empty."
430+
);
441431
}
432+
double average = moistureContentService.calculateAverage(riaKey, mcValueArray);
433+
return ResponseEntity.status(HttpStatus.OK).body(average);
434+
} catch (IllegalArgumentException e) {
435+
SparLog.error("Invalid input for calculateAverage: {}", e.getMessage(), e);
436+
throw new ResponseStatusException(
437+
HttpStatus.BAD_REQUEST,
438+
"Invalid input: " + e.getMessage(),
439+
e
440+
);
441+
442+
} catch (Exception e) {
443+
SparLog.error("Unexpected error in calculateAverage: {}", e.getMessage(), e);
444+
throw new ResponseStatusException(
445+
HttpStatus.INTERNAL_SERVER_ERROR,
446+
"An unexpected error occurred: " + e.getMessage(),
447+
e
448+
);
449+
}
442450
}
443451
}

oracle-api/src/test/java/ca/bc/gov/oracleapi/endpoint/consep/MoistureContentConesEndpointTest.java

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package ca.bc.gov.oracleapi.endpoint.consep;
22

3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
35
import static org.mockito.ArgumentMatchers.any;
6+
import static org.mockito.ArgumentMatchers.anyList;
47
import static org.mockito.ArgumentMatchers.eq;
58
import static org.mockito.Mockito.doNothing;
69
import static org.mockito.Mockito.doThrow;
@@ -21,6 +24,7 @@
2124
import ca.bc.gov.oracleapi.entity.consep.ActivityEntity;
2225
import ca.bc.gov.oracleapi.entity.consep.MccReplicateEntity;
2326
import ca.bc.gov.oracleapi.entity.consep.idclass.ReplicateId;
27+
import ca.bc.gov.oracleapi.exception.InvalidTestActivityKeyException;
2428
import ca.bc.gov.oracleapi.service.consep.ActivityService;
2529
import ca.bc.gov.oracleapi.service.consep.MoistureContentService;
2630
import ca.bc.gov.oracleapi.service.consep.TestResultService;
@@ -30,6 +34,8 @@
3034
import java.math.BigDecimal;
3135
import java.time.LocalDateTime;
3236
import java.time.format.DateTimeFormatter;
37+
import java.util.Arrays;
38+
import java.util.Collections;
3339
import java.util.List;
3440
import java.util.Optional;
3541
import org.junit.jupiter.api.BeforeEach;
@@ -503,4 +509,171 @@ void deleteReplicate_shouldReturnNotFound() throws Exception {
503509
replicateNumber).with(csrf().asHeader()).contentType(MediaType.APPLICATION_JSON))
504510
.andExpect(status().isNotFound());
505511
}
512+
513+
@Test
514+
@DisplayName("POST /{riaKey}/replicates - should delete multiple replicates")
515+
void deleteReplicates_shouldSucceed() throws Exception {
516+
BigDecimal riaKey = new BigDecimal("1234567890");
517+
List<Integer> replicateNumbers = Arrays.asList(1, 2, 3);
518+
519+
doNothing().when(moistureContentService).deleteMccReplicates(riaKey, replicateNumbers);
520+
521+
mockMvc.perform(post("/api/moisture-content-cone/{riaKey}/replicates", riaKey)
522+
.with(csrf().asHeader())
523+
.contentType(MediaType.APPLICATION_JSON)
524+
.content(objectMapper.writeValueAsString(replicateNumbers)))
525+
.andExpect(status().isOk())
526+
.andExpect(jsonPath("$[0]").value(1))
527+
.andExpect(jsonPath("$[1]").value(2))
528+
.andExpect(jsonPath("$[2]").value(3));
529+
}
530+
531+
@Test
532+
@DisplayName("POST /{riaKey}/replicates - should return 404 when replicates not found")
533+
void deleteReplicates_shouldReturnNotFound() throws Exception {
534+
BigDecimal riaKey = new BigDecimal("1234567890");
535+
List<Integer> replicateNumbers = Arrays.asList(1, 2, 3);
536+
537+
doThrow(new InvalidTestActivityKeyException())
538+
.when(moistureContentService).deleteMccReplicates(riaKey, replicateNumbers);
539+
540+
mockMvc.perform(post("/api/moisture-content-cone/{riaKey}/replicates", riaKey)
541+
.with(csrf().asHeader())
542+
.contentType(MediaType.APPLICATION_JSON)
543+
.content(objectMapper.writeValueAsString(replicateNumbers)))
544+
.andExpect(status().isNotFound());
545+
}
546+
547+
@Test
548+
@DisplayName("POST /{riaKey}/calculate-average - should calculate average successfully")
549+
void calculateAverage_shouldSucceed() throws Exception {
550+
BigDecimal riaKey = new BigDecimal("1234567890");
551+
List<Double> numbers = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0);
552+
double expectedAverage = 3.0;
553+
554+
when(moistureContentService.calculateAverage(riaKey, numbers)).thenReturn(expectedAverage);
555+
556+
mockMvc.perform(post("/api/moisture-content-cone/{riaKey}/calculate-average", riaKey)
557+
.with(csrf().asHeader())
558+
.contentType(MediaType.APPLICATION_JSON)
559+
.content(objectMapper.writeValueAsString(numbers)))
560+
.andExpect(status().isOk())
561+
.andExpect(jsonPath("$").value(expectedAverage));
562+
}
563+
564+
@Test
565+
@DisplayName("POST /{riaKey}/calculate-average - should return 400 for null list")
566+
void calculateAverage_shouldReturnBadRequestForNullList() throws Exception {
567+
BigDecimal riaKey = new BigDecimal("1234567890");
568+
569+
mockMvc.perform(post("/api/moisture-content-cone/{riaKey}/calculate-average", riaKey)
570+
.with(csrf().asHeader())
571+
.contentType(MediaType.APPLICATION_JSON)
572+
.content("null"))
573+
.andExpect(status().isBadRequest());
574+
}
575+
576+
@Test
577+
@DisplayName("POST /{riaKey}/calculate-average - should return 500 for service error")
578+
void calculateAverage_shouldReturnInternalServerError() throws Exception {
579+
BigDecimal riaKey = new BigDecimal("1234567890");
580+
List<Double> numbers = Arrays.asList(1.0, 2.0, 3.0);
581+
582+
when(moistureContentService.calculateAverage(riaKey, numbers))
583+
.thenThrow(new RuntimeException("Unexpected error"));
584+
585+
mockMvc.perform(post("/api/moisture-content-cone/{riaKey}/calculate-average", riaKey)
586+
.with(csrf().asHeader())
587+
.contentType(MediaType.APPLICATION_JSON)
588+
.content(objectMapper.writeValueAsString(numbers)))
589+
.andExpect(status().isInternalServerError());
590+
}
591+
592+
@Test
593+
@DisplayName("GET /validate/{riaKey} - should successfully validate data")
594+
void validateMoistureContentData_shouldSucceed() throws Exception {
595+
BigDecimal riaKey = new BigDecimal("1234567890");
596+
597+
// Mock data
598+
MoistureContentConesDto mockDto = new MoistureContentConesDto(
599+
1, "Sample", "STATUS", new BigDecimal("50.0"), 1,
600+
"REQ123", "SL123", "ACT", "TST", "Comment",
601+
LocalDateTime.now(), LocalDateTime.now(), Collections.emptyList()
602+
);
603+
604+
when(moistureContentService.getMoistureConeContentData(riaKey))
605+
.thenReturn(Optional.of(mockDto));
606+
607+
doNothing().when(moistureContentService)
608+
.validateMoistureConeContentData(anyList());
609+
610+
doNothing().when(activityService)
611+
.validateActivityData(any(ActivityEntity.class));
612+
613+
doNothing().when(testResultService)
614+
.updateTestResultStatusToCompleted(riaKey);
615+
616+
mockMvc.perform(get("/api/moisture-content-cone/validate/{riaKey}", riaKey)
617+
.with(csrf().asHeader()))
618+
.andExpect(status().isOk());
619+
}
620+
621+
@Test
622+
@DisplayName("GET /validate/{riaKey} - should return 400 when validation fails")
623+
void validateMoistureContentData_shouldReturnBadRequest() throws Exception {
624+
BigDecimal riaKey = new BigDecimal("1234567890");
625+
626+
MoistureContentConesDto mockDto = new MoistureContentConesDto(
627+
1, "Sample", "STATUS", new BigDecimal("50.0"), 1,
628+
"REQ123", "SL123", "ACT", "TST", "Comment",
629+
LocalDateTime.now(), LocalDateTime.now(), Collections.emptyList()
630+
);
631+
632+
when(moistureContentService.getMoistureConeContentData(riaKey))
633+
.thenReturn(Optional.of(mockDto));
634+
635+
doThrow(new IllegalArgumentException("Invalid moisture data"))
636+
.when(moistureContentService)
637+
.validateMoistureConeContentData(anyList());
638+
639+
mockMvc.perform(get("/api/moisture-content-cone/validate/{riaKey}", riaKey)
640+
.with(csrf().asHeader()))
641+
.andExpect(status().isBadRequest())
642+
.andExpect(result -> assertTrue(
643+
result.getResolvedException() instanceof ResponseStatusException))
644+
.andExpect(result -> assertEquals(
645+
"400 BAD_REQUEST \"Invalid moisture data\"",
646+
result.getResolvedException().getMessage()));
647+
}
648+
649+
@Test
650+
@DisplayName("GET /validate/{riaKey} - should return 400 when activity validation fails")
651+
void validateMoistureContentData_shouldReturnBadRequestForActivity() throws Exception {
652+
BigDecimal riaKey = new BigDecimal("1234567890");
653+
654+
MoistureContentConesDto mockDto = new MoistureContentConesDto(
655+
1, "Sample", "STATUS", new BigDecimal("50.0"), 1,
656+
"REQ123", "SL123", "ACT", "TST", "Comment",
657+
LocalDateTime.now(), LocalDateTime.now(), Collections.emptyList()
658+
);
659+
660+
when(moistureContentService.getMoistureConeContentData(riaKey))
661+
.thenReturn(Optional.of(mockDto));
662+
663+
doNothing().when(moistureContentService)
664+
.validateMoistureConeContentData(anyList());
665+
666+
doThrow(new IllegalArgumentException("Invalid activity data"))
667+
.when(activityService)
668+
.validateActivityData(any(ActivityEntity.class));
669+
670+
mockMvc.perform(get("/api/moisture-content-cone/validate/{riaKey}", riaKey)
671+
.with(csrf().asHeader()))
672+
.andExpect(status().isBadRequest())
673+
.andExpect(result -> assertTrue(
674+
result.getResolvedException() instanceof ResponseStatusException))
675+
.andExpect(result -> assertEquals(
676+
"400 BAD_REQUEST \"Invalid activity data\"",
677+
result.getResolvedException().getMessage()));
678+
}
506679
}
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
package ca.bc.gov.oracleapi.entity.consep;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import java.math.BigDecimal;
6+
import java.time.LocalDate;
7+
import java.time.LocalDateTime;
8+
import org.junit.jupiter.api.Test;
9+
10+
class ActivityEntityTest {
11+
12+
@Test
13+
void testAllGettersAndSetters() {
14+
ActivityEntity entity = new ActivityEntity();
15+
16+
BigDecimal decimalVal = new BigDecimal("123.45");
17+
Integer intVal = 42;
18+
LocalDate dateVal = LocalDate.of(2024, 6, 5);
19+
LocalDateTime dateTimeVal = LocalDateTime.of(2024, 6, 5, 12, 34, 56);
20+
21+
entity.setRiaKey(decimalVal);
22+
entity.setRequestId("REQ123456");
23+
entity.setRequestSkey(decimalVal);
24+
entity.setItemId("1");
25+
entity.setSeedlotNumber("S1234");
26+
entity.setFamilyLotNumber("FAMILY001");
27+
entity.setVegetationState("VEGST");
28+
entity.setStandardActivityId("STD");
29+
entity.setActivityTypeCode("ATC");
30+
entity.setTestCategoryCode("TCC");
31+
32+
entity.setEarliestStartDate(dateVal);
33+
entity.setLatestStartDate(dateVal);
34+
entity.setPlannedStartDate(dateVal);
35+
entity.setRevisedStartDate(dateVal);
36+
entity.setEarliestEndDate(dateVal);
37+
entity.setLatestEndDate(dateVal);
38+
entity.setPlannedEndDate(dateVal);
39+
entity.setRevisedEndDate(dateVal);
40+
41+
entity.setActualBeginDateTime(dateTimeVal);
42+
entity.setActualEndDateTime(dateTimeVal);
43+
entity.setActivityDuration(intVal);
44+
entity.setActivityTimeUnit("HRS");
45+
entity.setSignificantStatusIndicator(1);
46+
entity.setProcessCommitIndicator(1);
47+
entity.setUpdateTimestamp(dateTimeVal);
48+
entity.setProcessResultIndicator(0);
49+
entity.setTestResultIndicator(1);
50+
entity.setAssociatedRiaKey(decimalVal);
51+
entity.setWorkCentreId("WCI");
52+
entity.setBlendingMethod("BM1");
53+
entity.setDryerUsed("DU1");
54+
entity.setDeckType("DT1");
55+
entity.setDspMethod("DM1");
56+
57+
entity.setTotalSoakHours(intVal);
58+
entity.setTotalSoakMinutes(intVal);
59+
entity.setTargetFloaters(intVal);
60+
entity.setTargetSinkers(intVal);
61+
entity.setWaterTempMin(intVal);
62+
entity.setWaterTempMax(intVal);
63+
entity.setDewingMethod("DM2");
64+
entity.setAverageDrumSpeed("ADS");
65+
entity.setWaterTemp("WTC");
66+
67+
entity.setTotalHoursBatch(intVal);
68+
entity.setTotalMinutesBatch(intVal);
69+
entity.setTotalMistingMinutes(intVal);
70+
entity.setTotalMistingSeconds(intVal);
71+
entity.setDewingSeparation("DSE");
72+
entity.setHandDewing(1);
73+
entity.setProcessMachine("PMC");
74+
entity.setSepMachine("SMC");
75+
entity.setNoPneumatic(intVal);
76+
77+
entity.setDryWeight(decimalVal);
78+
entity.setPriorMoist(decimalVal);
79+
entity.setTargetFreshWeight(decimalVal);
80+
entity.setTargetMoistureContent(decimalVal);
81+
entity.setDrybackWeight(decimalVal);
82+
entity.setDrybackMoist(decimalVal);
83+
entity.setDryingMethod("DRY");
84+
entity.setTemperature(intVal);
85+
entity.setDepthPerTray(intVal);
86+
entity.setScreenMachineOne("SM1");
87+
entity.setScreenMachineTwo("SM2");
88+
entity.setScreenMachineThree("SM3");
89+
entity.setNoTimesRepeated(intVal);
90+
entity.setWaterType("WTP");
91+
entity.setTumblerType("TBT");
92+
entity.setTumblerSlope(intVal);
93+
entity.setTumblerRpm(decimalVal);
94+
entity.setIntermediateCleaner(1);
95+
entity.setClosedPercentage(intVal);
96+
entity.setSlightFlex(intVal);
97+
entity.setModerateFlex(intVal);
98+
entity.setFullFlex(intVal);
99+
entity.setKilnProgram("KILN");
100+
entity.setTurningPrfmd(1);
101+
entity.setHoursRequired(decimalVal);
102+
entity.setFilledSeedAverage(decimalVal);
103+
entity.setRiaComment("Sample comment");
104+
entity.setImbibedWeight(decimalVal);
105+
entity.setDrybackTime(intVal);
106+
entity.setTargetThirtyMoist(decimalVal);
107+
entity.setTargetThirtyFiveMoist(decimalVal);
108+
entity.setStratEndWeight(decimalVal);
109+
110+
// Assert sample fields
111+
assertThat(entity.getRiaKey()).isEqualByComparingTo(decimalVal);
112+
assertThat(entity.getRequestId()).isEqualTo("REQ123456");
113+
assertThat(entity.getActualBeginDateTime()).isEqualTo(dateTimeVal);
114+
assertThat(entity.getDryWeight()).isEqualByComparingTo(decimalVal);
115+
assertThat(entity.getKilnProgram()).isEqualTo("KILN");
116+
assertThat(entity.getRiaComment()).isEqualTo("Sample comment");
117+
assertThat(entity.getTestCategoryCode()).isEqualTo("TCC");
118+
assertThat(entity.getWaterTemp()).isEqualTo("WTC");
119+
assertThat(entity.getTurningPrfmd()).isEqualTo(1);
120+
}
121+
}

0 commit comments

Comments
 (0)