Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tests for service layer #954

Open
wants to merge 30 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
de942db
Made tests for ViolationServiceImpl, ValuesForUserTableServiceImpl an…
BranetE Jan 19, 2023
67c5f3b
Deleted Unused imports
BranetE Jan 19, 2023
413fd40
Merge branch 'dev' into tests_for_service_layer
BranetE Jan 19, 2023
a401d59
Formatted
BranetE Jan 20, 2023
9645e31
Merge branch 'dev' into tests_for_service_layer
BranetE Jan 20, 2023
a206824
Fixed issues with tests
BranetE Jan 20, 2023
ad07006
Created tests for AzureCloudStorageService
BranetE Jan 20, 2023
9511661
Added check if multipartFile is null and one test
BranetE Jan 20, 2023
8c7676d
Increased test coverage percentage for AzureCloudServiceTest
BranetE Jan 20, 2023
d1ced5b
Removed unnecessary exception constructor
BranetE Jan 20, 2023
c1fe53a
checkstyle fix
BranetE Jan 20, 2023
c0608c9
Added checks for exceptions
BranetE Jan 20, 2023
5989cbf
Update FileIsNullException.java
BranetE Jan 20, 2023
58e93b4
Fixed format
BranetE Jan 20, 2023
5e67e30
Tested contentClient
BranetE Jan 22, 2023
d90eaca
Created test for FileIsNullException
BranetE Jan 22, 2023
98f2ae7
Fixed checkAddUserViolationThrowsException() in ViolationServiceImplTest
BranetE Jan 22, 2023
d4727ca
Merge branch 'dev' into tests_for_service_layer
BranetE Jan 22, 2023
9016ba1
Removed unnecessary comments
BranetE Jan 23, 2023
b54037c
fixed some issues
BranetE Jan 23, 2023
b284bb9
Fix
BranetE Jan 23, 2023
eeb1fd3
Added IllegalArgumentException to handler and fixed code smell
BranetE Jan 23, 2023
ee7323d
Created test for containerClient()
BranetE Jan 23, 2023
0996600
Merge branch 'dev' into tests_for_service_layer
BranetE Jan 24, 2023
2eb82d5
fixed imports
BranetE Jan 24, 2023
e668ba9
Fixed fields check in checkUpload method an other
BranetE Jan 24, 2023
38ae02a
Removed unnecassary imports
BranetE Jan 24, 2023
f9c19f6
Added assertEquals to ValuesForUserTableServiceImplTest
BranetE Jan 24, 2023
0a6ecc6
Changed containerName
BranetE Jan 24, 2023
c6eea78
Fix
BranetE Jan 30, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
ConstraintViolationException.class,
MappingException.class,
CourierAlreadyExists.class,
ServiceAlreadyExistsException.class
ServiceAlreadyExistsException.class,
IllegalArgumentException.class
})
public final ResponseEntity<Object> handleBadRequestException(WebRequest request) {
ExceptionResponce exceptionResponse = new ExceptionResponce(getErrorAttributes(request));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public final class ErrorMessage {
public static final String ORDER_STATUS_NOT_FOUND = "Order status not found";
public static final String ORDER_PAYMENT_STATUS_NOT_FOUND = "Order payment status not found";
public static final String FILE_NOT_SAVED = "File hasn't been saved";
public static final String FILE_IS_NULL = "File equals null";
public static final String EMPLOYEE_NOT_FOUND = "Employee with current id doesn't exist: ";
public static final String EMPLOYEE_WITH_UUID_NOT_FOUND = "Employee with current uuid doesn't exist: ";
public static final String CURRENT_PHONE_NUMBER_ALREADY_EXISTS = "Employee with this phone number already exists: ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.google.common.annotations.VisibleForTesting;
import greencity.constant.ErrorMessage;
import greencity.exceptions.BadRequestException;
import greencity.exceptions.image.FileNotSavedException;
Expand Down Expand Up @@ -40,6 +41,9 @@ public AzureCloudStorageService(@Autowired PropertyResolver propertyResolver) {
*/
@Override
public String upload(MultipartFile multipartFile) {
if (multipartFile == null) {
throw new IllegalArgumentException(ErrorMessage.FILE_IS_NULL);
}
final String blob = UUID.randomUUID().toString();
BlobClient client = containerClient()
.getBlobClient(blob + multipartFile.getOriginalFilename());
Expand All @@ -65,7 +69,8 @@ public void delete(String url) {
}
}

private BlobContainerClient containerClient() {
@VisibleForTesting
BlobContainerClient containerClient() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add tests for this method too

BlobServiceClient serviceClient = new BlobServiceClientBuilder()
.connectionString(connectionString).buildClient();
return serviceClient.getBlobContainerClient(containerName);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package greencity.service.ubs;

import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import greencity.constant.ErrorMessage;
import greencity.exceptions.BadRequestException;
import greencity.exceptions.image.FileNotSavedException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.env.PropertyResolver;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;

@ExtendWith(MockitoExtension.class)
class AzureCloudStorageServiceTest {

@BeforeEach

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should after all class variables
https://www.cs.rice.edu/~cork/book/node9.html

void setUp() {
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty("azure.connection.string",
"DefaultEndpointsProtocol=https;AccountName=csb10032000a548f571;AccountKey=qV2VLVZlzxuEq8zGTgeiVE9puJiELNRPZcB9YgTSjZ3wKdWVA7kPjSOp6ESHlVMTJfHxB6N+iaV2TOlbe1GTvg==;EndpointSuffix=core.windows.net");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please do not use real values for tests

mockEnvironment.setProperty("azure.container.name", "allfiles");
propertyResolver = mockEnvironment;
azureCloudStorageService = spy(new AzureCloudStorageService(propertyResolver));
}

@Mock
private PropertyResolver propertyResolver;

private AzureCloudStorageService azureCloudStorageService;

@Mock
private BlobContainerClient containerClient;

@Mock
private BlobClient blobClient;

@Test
void checkUpload() {
MultipartFile multipartFile = new MockMultipartFile("Image", "Image".getBytes(StandardCharsets.UTF_8));
doReturn(containerClient).when(azureCloudStorageService).containerClient();
when(containerClient.getBlobClient(anyString())).thenReturn(blobClient);
doReturn("blobUrl").when(blobClient).getBlobUrl();
azureCloudStorageService.upload(multipartFile);
assertNotNull(azureCloudStorageService.getConnectionString());
Copy link

@RomaMocherniuk RomaMocherniuk Jan 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please check that values are equal to the values you set in the setUp method

assertNotNull(azureCloudStorageService.getContainerName());
assertEquals(propertyResolver.getProperty("azure.connection.string"),
azureCloudStorageService.getConnectionString());
assertEquals(propertyResolver.getProperty("azure.container.name"), azureCloudStorageService.getContainerName());
verify(containerClient).getBlobClient(anyString());
verify(blobClient).upload(any(InputStream.class), anyLong());
verify(blobClient).getBlobUrl();
}

@Test
void checkDelete() {
doReturn(containerClient).when(azureCloudStorageService).containerClient();
when(containerClient.getBlobClient(anyString())).thenReturn(blobClient);
when(blobClient.exists()).thenReturn(true);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add test if blobClient.exists() == null and blobClient.exists() == false

doNothing().when(blobClient).delete();
azureCloudStorageService.delete("url/somepath/somefile.txt");
assertNotNull(azureCloudStorageService.getConnectionString());
assertNotNull(azureCloudStorageService.getContainerName());
verify(containerClient).getBlobClient(anyString());
assertEquals(true, blobClient.exists());
verify(blobClient).delete();
}

@ParameterizedTest
@ValueSource(booleans = {false})
@NullSource
void checkDeleteIfClientNullOrFalse(Boolean exists) {
doReturn(containerClient).when(azureCloudStorageService).containerClient();
when(containerClient.getBlobClient(anyString())).thenReturn(blobClient);
when(blobClient.exists()).thenReturn(exists);
azureCloudStorageService.delete("url/somepath/somefile.txt");
verify(blobClient, never()).delete();
}

@Test
void checkUploadThrowsException() {
doReturn(containerClient).when(azureCloudStorageService).containerClient();
when(containerClient.getBlobClient(anyString())).thenReturn(blobClient);
doAnswer(invocation -> {
throw new IOException();
}).when(blobClient).upload(any(InputStream.class), anyLong());
MultipartFile multipartFile = new MockMultipartFile("Image", "Image".getBytes(StandardCharsets.UTF_8));
FileNotSavedException ex =
assertThrows(FileNotSavedException.class, () -> azureCloudStorageService.upload(multipartFile));
assertEquals(ErrorMessage.FILE_NOT_SAVED, ex.getMessage());
}

@Test
void checkUploadNullImage() {
MultipartFile multipartFile = null;
IllegalArgumentException ex =
assertThrows(IllegalArgumentException.class, () -> azureCloudStorageService.upload(multipartFile));
assertEquals(ErrorMessage.FILE_IS_NULL, ex.getMessage());
}

@Test
void checkInvalidConnectionString() {
azureCloudStorageService = new AzureCloudStorageService(new MockEnvironment());
assertThrows(IllegalArgumentException.class, () -> azureCloudStorageService.containerClient());
}

@Test
void checkContainerClient() {
BlobContainerClient client = azureCloudStorageService.containerClient();
assertEquals(propertyResolver.getProperty("azure.container.name"), client.getBlobContainerName());
}

@Test
void checkDeleteThrowsException() {
String url = "aa#26#1";
BadRequestException ex = assertThrows(BadRequestException.class, () -> azureCloudStorageService.delete(url));
assertEquals(ErrorMessage.PARSING_URL_FAILED + url, ex.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package greencity.service.ubs;

import greencity.ModelUtils;
import greencity.constant.ErrorMessage;
import greencity.entity.user.User;
import greencity.entity.user.employee.Employee;
import greencity.enums.SortingOrder;
import greencity.filters.CustomerPage;
import greencity.filters.UserFilterCriteria;
import greencity.repository.EmployeeRepository;
import greencity.repository.UserRepository;
import greencity.repository.UserTableRepo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.*;

import javax.persistence.EntityNotFoundException;
import java.util.*;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please do not use *


import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here


@ExtendWith(MockitoExtension.class)
class ValuesForUserTableServiceImplTest {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please follow encapsulation object-oriented principle


@Mock
private UserRepository userRepository;

@Mock
private UserTableRepo userTableRepo;

@Mock
private EmployeeRepository employeeRepository;

@InjectMocks
private ValuesForUserTableServiceImpl valuesForUserTableService;

@Test
void checkGetAllFields() {
User user = User.builder()
.orders(new ArrayList<>())
.violations(5)
.currentPoints(8)
.build();
Pageable pageable = PageRequest.of(1, 1);
Employee employee = ModelUtils.getEmployee();
List<Long> tariffsInfo = List.of(1L, 2L, 3L);
when(employeeRepository.findByEmail(anyString())).thenReturn(Optional.of(employee));
when(employeeRepository.findTariffsInfoForEmployee(anyLong())).thenReturn(tariffsInfo);
when(userRepository.getAllUsersByTariffsInfoId(anyLong())).thenReturn(tariffsInfo);
when(userTableRepo.findAll(any(UserFilterCriteria.class), anyString(), any(SortingOrder.class),
any(CustomerPage.class), Mockito.<Long>anyList())).thenReturn(new PageImpl<>(List.of(user), pageable, 1L));
valuesForUserTableService.getAllFields(new CustomerPage(), "column", SortingOrder.ASC, new UserFilterCriteria(),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please check if the result of valuesForUserTableService.getAllFields contains all expected values

employee.getEmail());
verify(employeeRepository).findByEmail(anyString());
verify(employeeRepository).findTariffsInfoForEmployee(anyLong());
verify(userRepository, times(tariffsInfo.size())).getAllUsersByTariffsInfoId(anyLong());
verify(userTableRepo).findAll(any(UserFilterCriteria.class), anyString(), any(SortingOrder.class),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please verify all mocks

any(CustomerPage.class), Mockito.<Long>anyList());
}

@Test
void checkGetAllFieldsIfEmployeeIsNull() {
CustomerPage customerPage = new CustomerPage();
UserFilterCriteria userFilterCriteria = new UserFilterCriteria();
EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> valuesForUserTableService
.getAllFields(customerPage, "column", SortingOrder.ASC, userFilterCriteria, "email"));
assertEquals(ErrorMessage.EMPLOYEE_NOT_FOUND, ex.getMessage());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import greencity.constant.ErrorMessage;
import greencity.entity.order.TariffsInfo;
import greencity.entity.user.employee.Employee;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -33,6 +37,8 @@
import greencity.repository.ViolationRepository;
import greencity.service.notification.NotificationServiceImpl;

import javax.persistence.EntityNotFoundException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.any;
Expand Down Expand Up @@ -105,35 +111,37 @@ void deleteViolationFromOrderByOrderId() {
}

@Test
@Disabled
void checkAddUserViolation() {
Employee employee = ModelUtils.getEmployee();
List<Long> tariffsInfos = List.of(1L, 2L, 3L);
TariffsInfo tariffsInfo = ModelUtils.getTariffsInfo();
User user = ModelUtils.getTestUser();
Order order = user.getOrders().get(0);
order.setTariffsInfo(tariffsInfo);
order.setUser(user);
AddingViolationsToUserDto add = ModelUtils.getAddingViolationsToUserDto();
add.setOrderID(order.getId());
when(orderRepository.findById(order.getId())).thenReturn(Optional.ofNullable(order));
when(userRepository.findUserByUuid("abc")).thenReturn(Optional.of(user));
when(userRepository.countTotalUsersViolations(1L)).thenReturn(1);
when(employeeRepository.findByEmail(anyString())).thenReturn(Optional.ofNullable(employee));
when(employeeRepository.findTariffsInfoForEmployee(anyLong())).thenReturn(tariffsInfos);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add verify for all mocks

violationService.addUserViolation(add, new MultipartFile[2], "abc");

assertEquals(1, user.getViolations());
}

@Test
@Disabled

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please remove import for Disabled

void checkAddUserViolationThrowsException() {
User user = ModelUtils.getTestUser();
Order order = user.getOrders().get(0);
order.setUser(user);
AddingViolationsToUserDto add = ModelUtils.getAddingViolationsToUserDto();
add.setOrderID(order.getId());
when(orderRepository.findById(order.getId())).thenReturn(Optional.ofNullable(order));
when(userRepository.findUserByUuid("abc")).thenReturn(Optional.of(user));
when(violationRepository.findByOrderId(order.getId())).thenReturn(Optional.of(ModelUtils.getViolation()));

assertThrows(NotFoundException.class,
EntityNotFoundException ex = assertThrows(EntityNotFoundException.class,
() -> violationService.addUserViolation(add, new MultipartFile[2], "abc"));
assertEquals(ErrorMessage.EMPLOYEE_NOT_FOUND, ex.getMessage());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add verify for orderRepository.findById(order.getId())).thenReturn(Optional.ofNullable(order)

}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mock-maker-inline