Skip to content
Snippets Groups Projects
Commit ac71a377 authored by Anders Austlid's avatar Anders Austlid
Browse files

Added new tests for several controller classes

parent 2418084b
No related branches found
No related tags found
No related merge requests found
package ntnu.idatt2016.v233.SmartMat.controller; 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.dto.request.LoginRequest;
import ntnu.idatt2016.v233.SmartMat.service.TokenService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.ResponseEntity;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.authentication.AuthenticationManager; 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.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collection; import static org.mockito.Mockito.*;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*; class AuthenticationControllerTest {
import static org.mockito.ArgumentMatchers.any; private TokenService tokenService;
import static org.mockito.Mockito.when;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class AuthenticationControllerTest {
/**
@MockBean
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
private AuthenticationController authenticationController;
@BeforeEach
void setUp() {
tokenService = mock(TokenService.class);
authenticationManager = mock(AuthenticationManager.class);
authenticationController = new AuthenticationController(tokenService, authenticationManager);
}
@Test @Test
public void token_validCredentials_shouldReturnToken() { void testToken_success() {
LoginRequest loginRequest = new LoginRequest("kari123", "sjokoladekake"); 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() { when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
@Override validLoginRequest.username(),
public Collection<? extends GrantedAuthority> getAuthorities() { validLoginRequest.password()
return List.of(new SimpleGrantedAuthority(Authority.USER.toString())); ))).thenReturn(authentication);
}
@Override when(tokenService.generateToken(authentication)).thenReturn(expectedToken);
public Object getCredentials() {
return "test";
}
@Override ResponseEntity<?> response = authenticationController.token(validLoginRequest);
public Object getDetails() {
return "test";
}
@Override assertEquals(HttpStatus.OK, response.getStatusCode());
public Object getPrincipal() { assertEquals(expectedToken, response.getBody());
return "test"; }
}
@Override @Test
public boolean isAuthenticated() { void testToken_invalidInput() {
return true; LoginRequest invalidLoginRequest = new LoginRequest("invalid_username", "");
}
@Override ResponseEntity<?> response = authenticationController.token(invalidLoginRequest);
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
} assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertEquals("Error: Invalid input.", response.getBody());
}
@Override @Test
public String getName() { void testToken_invalidCredentials() {
return "test"; 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(); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
rb.setConnectTimeout(Duration.ofSeconds(10)); assertEquals("Error: Invalid username or password.", response.getBody());
rb.setReadTimeout(Duration.ofSeconds(10)); }
rb.requestFactory(() -> new HttpComponentsClientHttpRequestFactory());
rb.errorHandler(new DefaultResponseErrorHandler(){
protected boolean hasError(HttpStatus statusCode) {
return statusCode.is5xxServerError();
}
});
@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()); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
assertNotNull(responseEntity.getBody()); assertEquals("Error: Unable to generate token. Please try again later.", response.getBody());
assertFalse(responseEntity.getBody().isEmpty());
} }
*/
} }
...@@ -31,7 +31,6 @@ public class ShoppingListControllerTest { ...@@ -31,7 +31,6 @@ public class ShoppingListControllerTest {
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
shoppingList = new ShoppingList(); shoppingList = new ShoppingList();
// Set properties for the shoppingList object
} }
......
...@@ -31,7 +31,6 @@ public class WeeklyMenuControllerTest { ...@@ -31,7 +31,6 @@ public class WeeklyMenuControllerTest {
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
weeklyMenu = new ArrayList<>(); weeklyMenu = new ArrayList<>();
// Add WeeklyMenuResponse objects to the weeklyMenu list
weeklyMenu.add(WeeklyMenuResponse.builder() weeklyMenu.add(WeeklyMenuResponse.builder()
.recipeId(1) .recipeId(1)
.recipeName("Recipe1") .recipeName("Recipe1")
...@@ -49,7 +48,7 @@ public class WeeklyMenuControllerTest { ...@@ -49,7 +48,7 @@ public class WeeklyMenuControllerTest {
@Test @Test
public void getWeeklyMenu_found() { public void getWeeklyMenu_found() {
Long fridgeId = 1L; long fridgeId = 1L;
when(weeklyMenuService.getWeeklyMenu(fridgeId)).thenReturn(weeklyMenu); when(weeklyMenuService.getWeeklyMenu(fridgeId)).thenReturn(weeklyMenu);
ResponseEntity<List<WeeklyMenuResponse>> response = weeklyMenuController.getWeeklyMenu(fridgeId); ResponseEntity<List<WeeklyMenuResponse>> response = weeklyMenuController.getWeeklyMenu(fridgeId);
...@@ -60,7 +59,7 @@ public class WeeklyMenuControllerTest { ...@@ -60,7 +59,7 @@ public class WeeklyMenuControllerTest {
@Test @Test
public void getWeeklyMenu_notFound() { public void getWeeklyMenu_notFound() {
Long fridgeId = 1L; long fridgeId = 1L;
when(weeklyMenuService.getWeeklyMenu(fridgeId)).thenReturn(new ArrayList<>()); when(weeklyMenuService.getWeeklyMenu(fridgeId)).thenReturn(new ArrayList<>());
ResponseEntity<List<WeeklyMenuResponse>> response = weeklyMenuController.getWeeklyMenu(fridgeId); ResponseEntity<List<WeeklyMenuResponse>> response = weeklyMenuController.getWeeklyMenu(fridgeId);
......
...@@ -26,7 +26,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. ...@@ -26,7 +26,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@ExtendWith(SpringExtension.class) @ExtendWith(SpringExtension.class)
@WebMvcTest(FridgeController.class) @WebMvcTest(FridgeController.class)
@AutoConfigureMockMvc(addFilters = false) // Disables security for this test class @AutoConfigureMockMvc(addFilters = false)
public class FridgeControllerTest { public class FridgeControllerTest {
@Autowired @Autowired
......
package ntnu.idatt2016.v233.SmartMat.controller.group; 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.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.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.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.springframework.beans.factory.annotation.Autowired;
import org.mockito.Mock; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.HttpStatus; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.ResponseEntity; 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.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(SpringExtension.class)
import static org.mockito.ArgumentMatchers.any; @WebMvcTest(WasteController.class)
import static org.mockito.Mockito.*; @AutoConfigureMockMvc(addFilters = false)
@ExtendWith(MockitoExtension.class)
public class WasteControllerTest { public class WasteControllerTest {
@InjectMocks @Autowired
private WasteController wasteController; private MockMvc mockMvc;
@Mock @Autowired
private ObjectMapper objectMapper;
@MockBean
private WasteService wasteService; private WasteService wasteService;
private Waste waste; private Group group;
/** private Product product;
private WasteRequest wasteRequest;
private Waste expectedWaste;
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
waste = Waste.builder() group = new Group();
.wasteId(1L) group.setGroupId(1L);
.groupId(1L) group.setGroupName("TestGroup");
.ean(123456789L)
.timestamp(new Timestamp(System.currentTimeMillis())) product = new Product();
.amount(5.5) product.setEan(12345678L);
.unit("kg")
.build(); 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 @Test
public void testCreateWaste() { public void testCreateWaste() throws Exception {
when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.empty()); when(wasteService.createWaste(wasteRequest)).thenReturn(Optional.of(expectedWaste));
when(wasteService.createWaste(any(Waste.class))).thenReturn(waste);
ResponseEntity<Waste> response = wasteController.createWaste(waste);
assertEquals(HttpStatus.OK, response.getStatusCode()); mockMvc.perform(post("/api/waste/waste")
assertEquals(waste, response.getBody()); .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(wasteRequest);
verify(wasteService, times(1)).createWaste(any(Waste.class));
} }
@Test @Test
public void testCreateWaste_badRequest() { public void testGetWasteOfCategoryByGroupId() throws Exception {
when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.of(waste)); 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, times(1)).getWasteOfCategoryByGroupId(group.getGroupId(), categoryName);
verify(wasteService, never()).createWaste(any(Waste.class));
} }
@Test @Test
public void testGetWasteById_found() { public void testGetInformationOfCakeGraph() throws Exception {
when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.of(waste)); 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()); mockMvc.perform(get("/api/waste/statistic/cakeGraph/{groupId}", group.getGroupId()))
assertEquals(waste, response.getBody()); .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 @Test
public void testGetWasteById_notFound() { public void testGetWasteById_NotFound() throws Exception {
when(wasteService.getWasteById(waste.getWasteId())).thenReturn(Optional.empty()); 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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment