diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeController.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeController.java index cc4e140cbd070b1f211fffebb3b4a6a86669f820..bf2861a67a389e5c622f9e6299ea08b60f883650 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeController.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeController.java @@ -2,7 +2,9 @@ package ntnu.idatt2016.v233.SmartMat.controller.group; import lombok.AllArgsConstructor; import ntnu.idatt2016.v233.SmartMat.dto.request.FridgeProductRequest; +import ntnu.idatt2016.v233.SmartMat.entity.fridgeProduct.FridgeProductAsso; import ntnu.idatt2016.v233.SmartMat.entity.group.Fridge; +import ntnu.idatt2016.v233.SmartMat.entity.product.Product; import ntnu.idatt2016.v233.SmartMat.service.group.FridgeService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -56,12 +58,12 @@ public class FridgeController { * @return success if the product was added, bad request if the product was already in the fridge, or not found if the group or product doesn't exist */ @PostMapping("/group/product") - public ResponseEntity<Object> addProductToFridge(@RequestBody FridgeProductRequest request) { + public ResponseEntity<Product> addProductToFridge(@RequestBody FridgeProductRequest request) { return fridgeService.addProductToFridge(request).map(ResponseEntity::ok).orElseGet(()-> ResponseEntity.notFound().build()); } @PutMapping("/group/product") - public ResponseEntity<Object> updateProductInFridge(@RequestBody FridgeProductRequest request) { + public ResponseEntity<FridgeProductAsso> updateProductInFridge(@RequestBody FridgeProductRequest request) { return fridgeService.updateProductInFridge(request).map(ResponseEntity::ok).orElseGet(()-> ResponseEntity.notFound().build()); } diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/FridgeService.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/FridgeService.java index 9071dfa5f38b503f8519af0a5b80a20aa4eaddc0..1e8c9cd1bc85818abd40768c4af6bb8889a5add5 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/FridgeService.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/FridgeService.java @@ -69,7 +69,7 @@ public class FridgeService { * @param fridgeProductRequest the fridge product request * @return the product that was added to the fridge */ - public Optional<Object> addProductToFridge(FridgeProductRequest fridgeProductRequest) { + public Optional<Product> addProductToFridge(FridgeProductRequest fridgeProductRequest) { Optional<Product> product = productService.getProductById(fridgeProductRequest.ean()); Optional<Fridge> fridge = fridgeRepository.findByGroupGroupId(fridgeProductRequest.groupId()); double price = 100.0; @@ -89,11 +89,11 @@ public class FridgeService { .build()); fridgeRepository.save(fridge.get()); - return Optional.of(product); + return product; } - public Optional<Object> updateProductInFridge(FridgeProductRequest request) { + public Optional<FridgeProductAsso> updateProductInFridge(FridgeProductRequest request) { Optional<FridgeProductAsso> fridgeProductAsso = fridgeProductAssoRepo.findById(request.fridgeProductId()); if (fridgeProductAsso.isEmpty()) return Optional.empty(); @@ -108,7 +108,7 @@ public class FridgeService { fridgeProductAssoRepo.save(fridgeProductAsso.get()); - return Optional.of(fridgeProductAsso); + return fridgeProductAsso; } @@ -164,12 +164,12 @@ public class FridgeService { * @param amount the amount to delete * @return an optional containing the fridge product if it exists */ - public Optional<Object> deleteAmountFromFridge(long fridgeProductId, double amount) { + public Optional<FridgeProductAsso> deleteAmountFromFridge(long fridgeProductId, double amount) { Optional<FridgeProductAsso> fridgeProductAsso = fridgeProductAssoRepo.findAllById(fridgeProductId); if(fridgeProductAsso.isEmpty()) return Optional.empty(); FridgeProductAsso fridgeProductAsso1 = fridgeProductAsso.get(); if(amount < fridgeProductAsso1.getAmount() ){ - fridgeProductAsso1.setAmount(fridgeProductAsso1.getAmount() -amount); + fridgeProductAsso1.setAmount(fridgeProductAsso1.getAmount() - amount); return Optional.of(fridgeProductAssoRepo.save(fridgeProductAsso1)); } else { Group group = fridgeProductAsso1.getFridgeId().getGroup(); @@ -177,7 +177,7 @@ public class FridgeService { group.setLevel(GroupUtil.getLevel(group.getPoints())); groupRepository.save(group); fridgeProductAssoRepo.delete(fridgeProductAsso.get()); - return Optional.of(true); + return Optional.empty(); } } @@ -186,7 +186,7 @@ public class FridgeService { * @param fridgeProductId the ID of the fridge product association to delete * @return an Optional containing the saved waste object, or an empty Optional if the fridge product association with the given ID is not found */ - public Optional<Object> wasteProductFromFridge(long fridgeProductId){ + public Optional<Waste> wasteProductFromFridge(long fridgeProductId){ Optional<FridgeProductAsso> fridgeProductAsso = fridgeProductAssoRepo.findById(fridgeProductId); if(fridgeProductAsso.isEmpty()) return Optional.empty(); FridgeProductAsso fridgeProductAsso1 = fridgeProductAsso.get(); @@ -197,7 +197,13 @@ public class FridgeService { group.setLevel(GroupUtil.getLevel(group.getPoints())); } groupRepository.save(group); - return Optional.of(wasteRepository.save(Waste.builder().buyPrice(fridgeProductAsso1.getBuyPrice()).amount(fridgeProductAsso1.getAmount()).unit(fridgeProductAsso1.getEan().getUnit()).ean(fridgeProductAsso1.getEan()).groupId(fridgeProductAsso1.getFridgeId().getGroup()).timestamp(new Timestamp(System.currentTimeMillis())).build())); + return Optional.of(wasteRepository.save(Waste.builder() + .amount(fridgeProductAsso1.getAmount()) + .unit(fridgeProductAsso1.getEan().getUnit()) + .ean(fridgeProductAsso1.getEan()) + .groupId(fridgeProductAsso1.getFridgeId().getGroup()) + .timestamp(new Timestamp(System.currentTimeMillis())) + .build())); } diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/AuthenticationControllerTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/AuthenticationControllerTest.java index e0b84012283c7ed61bd1fd462a94a079899a3fed..bb30a2a4077f7b4c1cab472b371f18d4ff402154 100644 --- a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/AuthenticationControllerTest.java +++ b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/AuthenticationControllerTest.java @@ -1,100 +1,92 @@ package ntnu.idatt2016.v233.SmartMat.controller; -import ntnu.idatt2016.v233.SmartMat.dto.enums.Authority; import ntnu.idatt2016.v233.SmartMat.dto.request.LoginRequest; +import ntnu.idatt2016.v233.SmartMat.service.TokenService; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.http.*; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.web.client.DefaultResponseErrorHandler; -import org.springframework.web.client.RestTemplate; +import org.springframework.security.core.AuthenticationException; -import java.time.Duration; -import java.util.Collection; -import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) - -public class AuthenticationControllerTest { -/** - @MockBean +class AuthenticationControllerTest { + private TokenService tokenService; private AuthenticationManager authenticationManager; + private AuthenticationController authenticationController; + @BeforeEach + void setUp() { + tokenService = mock(TokenService.class); + authenticationManager = mock(AuthenticationManager.class); + authenticationController = new AuthenticationController(tokenService, authenticationManager); + } @Test - public void token_validCredentials_shouldReturnToken() { - LoginRequest loginRequest = new LoginRequest("kari123", "sjokoladekake"); + void testToken_success() { + String expectedToken = "generated_token"; + LoginRequest validLoginRequest = new LoginRequest("valid_user", "valid_password"); + Authentication authentication = mock(Authentication.class); - when(authenticationManager.authenticate(any(Authentication.class))).thenReturn(new Authentication() { - @Override - public Collection<? extends GrantedAuthority> getAuthorities() { - return List.of(new SimpleGrantedAuthority(Authority.USER.toString())); - } + when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( + validLoginRequest.username(), + validLoginRequest.password() + ))).thenReturn(authentication); - @Override - public Object getCredentials() { - return "test"; - } + when(tokenService.generateToken(authentication)).thenReturn(expectedToken); - @Override - public Object getDetails() { - return "test"; - } + ResponseEntity<?> response = authenticationController.token(validLoginRequest); - @Override - public Object getPrincipal() { - return "test"; - } + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals(expectedToken, response.getBody()); + } - @Override - public boolean isAuthenticated() { - return true; - } + @Test + void testToken_invalidInput() { + LoginRequest invalidLoginRequest = new LoginRequest("invalid_username", ""); - @Override - public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { + ResponseEntity<?> response = authenticationController.token(invalidLoginRequest); - } + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals("Error: Invalid input.", response.getBody()); + } - @Override - public String getName() { - return "test"; - } - }); + @Test + void testToken_invalidCredentials() { + LoginRequest invalidCredentialsRequest = new LoginRequest("invalid_user", "invalid_password"); + when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( + invalidCredentialsRequest.username(), + invalidCredentialsRequest.password() + ))).thenThrow(new BadCredentialsException("Invalid username or password.")); + ResponseEntity<?> response = authenticationController.token(invalidCredentialsRequest); - RestTemplateBuilder rb = new RestTemplateBuilder(); - rb.setConnectTimeout(Duration.ofSeconds(10)); - rb.setReadTimeout(Duration.ofSeconds(10)); - rb.requestFactory(() -> new HttpComponentsClientHttpRequestFactory()); - rb.errorHandler(new DefaultResponseErrorHandler(){ - protected boolean hasError(HttpStatus statusCode) { - return statusCode.is5xxServerError(); - } - }); + assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); + assertEquals("Error: Invalid username or password.", response.getBody()); + } + @Test + void testToken_tokenGenerationFailure() { + LoginRequest validLoginRequest = new LoginRequest("valid_user", "valid_password"); + Authentication authentication = mock(Authentication.class); - RestTemplate restTemplate = rb.build(); + when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( + validLoginRequest.username(), + validLoginRequest.password() + ))).thenReturn(authentication); + when(tokenService.generateToken(authentication)).thenThrow(RuntimeException.class); - ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8080/api/auth/credentials", loginRequest, String.class); + ResponseEntity<?> response = authenticationController.token(validLoginRequest); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertNotNull(responseEntity.getBody()); - assertFalse(responseEntity.getBody().isEmpty()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals("Error: Unable to generate token. Please try again later.", response.getBody()); } - */ - } diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/ShoppingListControllerTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/ShoppingListControllerTest.java index 3e8b471a117f1768018d8eb39529c7aa291b801a..04b1935e766b21b94a2acc063927598aca5fa024 100644 --- a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/ShoppingListControllerTest.java +++ b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/ShoppingListControllerTest.java @@ -31,7 +31,6 @@ public class ShoppingListControllerTest { @BeforeEach public void setUp() { shoppingList = new ShoppingList(); - // Set properties for the shoppingList object } diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/WeeklyMenuControllerTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/WeeklyMenuControllerTest.java index d6840e065c56c52ff4a6f7ddb0a003ea11bdec48..17a69d722937f5e6ca9b965b0dde30c167e693b9 100644 --- a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/WeeklyMenuControllerTest.java +++ b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/WeeklyMenuControllerTest.java @@ -31,7 +31,6 @@ public class WeeklyMenuControllerTest { @BeforeEach public void setUp() { weeklyMenu = new ArrayList<>(); - // Add WeeklyMenuResponse objects to the weeklyMenu list weeklyMenu.add(WeeklyMenuResponse.builder() .recipeId(1) .recipeName("Recipe1") @@ -49,7 +48,7 @@ public class WeeklyMenuControllerTest { @Test public void getWeeklyMenu_found() { - Long fridgeId = 1L; + long fridgeId = 1L; when(weeklyMenuService.getWeeklyMenu(fridgeId)).thenReturn(weeklyMenu); ResponseEntity<List<WeeklyMenuResponse>> response = weeklyMenuController.getWeeklyMenu(fridgeId); @@ -60,7 +59,7 @@ public class WeeklyMenuControllerTest { @Test public void getWeeklyMenu_notFound() { - Long fridgeId = 1L; + long fridgeId = 1L; when(weeklyMenuService.getWeeklyMenu(fridgeId)).thenReturn(new ArrayList<>()); ResponseEntity<List<WeeklyMenuResponse>> response = weeklyMenuController.getWeeklyMenu(fridgeId); diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeControllerTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..307be4db9141b3099e236fc6f67d7bc84f99f643 --- /dev/null +++ b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeControllerTest.java @@ -0,0 +1,144 @@ +package ntnu.idatt2016.v233.SmartMat.controller.group; + +import com.fasterxml.jackson.databind.ObjectMapper; +import ntnu.idatt2016.v233.SmartMat.dto.request.FridgeProductRequest; +import ntnu.idatt2016.v233.SmartMat.entity.fridgeProduct.FridgeProductAsso; +import ntnu.idatt2016.v233.SmartMat.entity.group.Fridge; +import ntnu.idatt2016.v233.SmartMat.entity.product.Product; +import ntnu.idatt2016.v233.SmartMat.service.group.FridgeService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(FridgeController.class) +@AutoConfigureMockMvc(addFilters = false) +public class FridgeControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockBean + private FridgeService fridgeService; + + private Fridge fridge; + private Product product; + private FridgeProductAsso fridgeProductAsso; + private FridgeProductRequest fridgeProductRequest; + + @BeforeEach + public void setUp() { + // Create and set up your test data here + fridge = new Fridge(); + product = new Product(); + fridgeProductAsso = new FridgeProductAsso(); + fridgeProductRequest = new FridgeProductRequest(1L, 1L, 1L, 2, 7, 100); + } + + @Test + public void getFridgeByGroupId() throws Exception { + when(fridgeService.getFridgeByGroupId(1L)).thenReturn(Optional.of(fridge)); + + mockMvc.perform(get("/api/fridges/group/1")) + .andExpect(status().isOk()); + } + + @Test + public void getFridgeByGroupId_notFound() throws Exception { + when(fridgeService.getFridgeByGroupId(1L)).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/fridges/group/1")) + .andExpect(status().isNotFound()); + } + + @Test + public void getFridgeByFridgeId() throws Exception { + when(fridgeService.getFridgeByFridgeId(1L)).thenReturn(Optional.of(fridge)); + + mockMvc.perform(get("/api/fridges/fridge/1")) + .andExpect(status().isOk()); + } + + @Test + public void getFridgeByFridgeId_notFound() throws Exception { + when(fridgeService.getFridgeByFridgeId(1L)).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/fridges/fridge/1")) + .andExpect(status().isNotFound()); + } + + @Test + public void addProductToFridge() throws Exception { + when(fridgeService.addProductToFridge(any(FridgeProductRequest.class))).thenReturn(Optional.of(product)); + + mockMvc.perform(post("/api/fridges/group/product") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(fridgeProductRequest))) + .andExpect(status().isOk()); + } + + @Test + public void addProductToFridge_notFound() throws Exception { + when(fridgeService.addProductToFridge(any(FridgeProductRequest.class))).thenReturn(Optional.empty()); + + mockMvc.perform(post("/api/fridges/group/product") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(fridgeProductRequest))) + .andExpect(status().isNotFound()); + } + + @Test + public void updateProductInFridge() throws Exception { + when(fridgeService.updateProductInFridge(any(FridgeProductRequest.class))).thenReturn(Optional.of(fridgeProductAsso)); + + mockMvc.perform(put("/api/fridges/group/product") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(fridgeProductRequest))) + .andExpect(status().isOk()); + } + + @Test + public void updateProductInFridge_notFound() throws Exception { + when(fridgeService.updateProductInFridge(any(FridgeProductRequest.class))).thenReturn(Optional.empty()); + + mockMvc.perform(put("/api/fridges/group/product") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(fridgeProductRequest))) + .andExpect(status().isNotFound()); + } + + @Test + public void removeProductFromFridge_success() throws Exception { + when(fridgeService.removeProductFromFridge(1L)).thenReturn(true); + + mockMvc.perform(delete("/api/fridges/delete/product/1")) + .andExpect(status().isOk()) + .andExpect(content().string("Success")); + } + + @Test + public void removeProductFromFridge_badRequest() throws Exception { + when(fridgeService.removeProductFromFridge(1L)).thenReturn(false); + + mockMvc.perform(delete("/api/fridges/delete/product/1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string("Product not found in the fridge")); + } +} diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/GroupControllerTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/GroupControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/WasteControllerTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/WasteControllerTest.java index 83b2e438885ecf28c83151c3ea0947057bb10455..ecfd1d94343190ba72264cf33a8c8f424668611e 100644 --- a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/WasteControllerTest.java +++ b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/WasteControllerTest.java @@ -1,93 +1,132 @@ package ntnu.idatt2016.v233.SmartMat.controller.group; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import ntnu.idatt2016.v233.SmartMat.dto.request.WasteRequest; +import ntnu.idatt2016.v233.SmartMat.entity.group.Group; +import ntnu.idatt2016.v233.SmartMat.entity.product.Product; import ntnu.idatt2016.v233.SmartMat.entity.Waste; +import ntnu.idatt2016.v233.SmartMat.entity.group.Group; +import ntnu.idatt2016.v233.SmartMat.entity.product.Product; import ntnu.idatt2016.v233.SmartMat.service.group.WasteService; +import ntnu.idatt2016.v233.SmartMat.util.CategoryUtil; +import org.aspectj.lang.annotation.Before; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; import java.sql.Timestamp; +import java.util.Arrays; +import java.util.List; import java.util.Optional; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) +@ExtendWith(SpringExtension.class) +@WebMvcTest(WasteController.class) +@AutoConfigureMockMvc(addFilters = false) public class WasteControllerTest { - @InjectMocks - private WasteController wasteController; + @Autowired + private MockMvc mockMvc; - @Mock + @Autowired + private ObjectMapper objectMapper; + + @MockBean private WasteService wasteService; - private Waste waste; -/** + private Group group; + private Product product; + private WasteRequest wasteRequest; + private Waste expectedWaste; + @BeforeEach public void setUp() { - waste = Waste.builder() - .wasteId(1L) - .groupId(1L) - .ean(123456789L) - .timestamp(new Timestamp(System.currentTimeMillis())) - .amount(5.5) - .unit("kg") - .build(); + group = new Group(); + group.setGroupId(1L); + group.setGroupName("TestGroup"); + + product = new Product(); + product.setEan(12345678L); + + wasteRequest = new WasteRequest(1L, 12345678L, 0.5, "kg"); + + expectedWaste = new Waste(); + expectedWaste.setWasteId(1L); + expectedWaste.setGroupId(group); + expectedWaste.setEan(product); + expectedWaste.setTimestamp(new Timestamp(System.currentTimeMillis())); + expectedWaste.setAmount(0.5); + expectedWaste.setUnit("kg"); } + // Test cases go here @Test - public void testCreateWaste() { - when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.empty()); - when(wasteService.createWaste(any(Waste.class))).thenReturn(waste); - - ResponseEntity<Waste> response = wasteController.createWaste(waste); + public void testCreateWaste() throws Exception { + when(wasteService.createWaste(wasteRequest)).thenReturn(Optional.of(expectedWaste)); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(waste, response.getBody()); + mockMvc.perform(post("/api/waste/waste") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(wasteRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("wasteId").value(expectedWaste.getWasteId())); - verify(wasteService, times(1)).getWasteById(waste.getWasteId()); - verify(wasteService, times(1)).createWaste(any(Waste.class)); + verify(wasteService, times(1)).createWaste(wasteRequest); } @Test - public void testCreateWaste_badRequest() { - when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.of(waste)); + public void testGetWasteOfCategoryByGroupId() throws Exception { + int categoryNumber = 1; + String categoryName = CategoryUtil.getCategoryName(categoryNumber); + List<Waste> expectedWastes = Arrays.asList(new Waste(/*...*/), new Waste(/*...*/)); - ResponseEntity<Waste> response = wasteController.createWaste(waste); + when(wasteService.getWasteOfCategoryByGroupId(group.getGroupId(), categoryName)).thenReturn(Optional.of(expectedWastes)); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + mockMvc.perform(get("/api/waste/group/{groupId}/category/{categoryNumber}", group.getGroupId(), categoryNumber)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].wasteId").value(expectedWastes.get(0).getWasteId())) + .andExpect(jsonPath("$[1].wasteId").value(expectedWastes.get(1).getWasteId())); - verify(wasteService, times(1)).getWasteById(waste.getWasteId()); - verify(wasteService, never()).createWaste(any(Waste.class)); + verify(wasteService, times(1)).getWasteOfCategoryByGroupId(group.getGroupId(), categoryName); } @Test - public void testGetWasteById_found() { - when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.of(waste)); + public void testGetInformationOfCakeGraph() throws Exception { + double[] expectedData = new double[]{0.3, 0.2, 0.5}; - ResponseEntity<Waste> response = wasteController.getWasteById(waste.getWasteId()); + when(wasteService.getCakeDiagram(group.getGroupId())).thenReturn(Optional.of(expectedData)); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(waste, response.getBody()); + mockMvc.perform(get("/api/waste/statistic/cakeGraph/{groupId}", group.getGroupId())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))) + .andExpect(jsonPath("$[0]").value(expectedData[0])) + .andExpect(jsonPath("$[1]").value(expectedData[1])) + .andExpect(jsonPath("$[2]").value(expectedData[2])); - verify(wasteService, times(1)).getWasteById(waste.getWasteId()); + verify(wasteService, times(1)).getCakeDiagram(group.getGroupId()); } @Test - public void testGetWasteById_notFound() { - when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.empty()); + public void testGetWasteById_NotFound() throws Exception { + long nonExistingWasteId = 99L; - ResponseEntity<Waste> response = wasteController.getWasteById(waste.getWasteId()); + when(wasteService.getWasteById(nonExistingWasteId)).thenReturn(Optional.empty()); - assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + mockMvc.perform(get("/api/waste/{wasteId}", nonExistingWasteId)) + .andExpect(status().isNotFound()); - verify(wasteService, times(1)).getWasteById(waste.getWasteId()); + verify(wasteService, times(1)).getWasteById(nonExistingWasteId); } - */ -} \ No newline at end of file +}