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 index fcfc26930462979000077ecde7551c47148c47f1..8e382735d7f1bb54ecf48a4ebcb7377425e852b3 100644 --- a/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeControllerTest.java +++ b/src/test/java/ntnu/idatt2016/v233/SmartMat/controller/group/FridgeControllerTest.java @@ -26,7 +26,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ExtendWith(SpringExtension.class) @WebMvcTest(FridgeController.class) -@AutoConfigureMockMvc(addFilters = false) // Disables security for this test class +@AutoConfigureMockMvc(addFilters = false) public class FridgeControllerTest { @Autowired 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 +}