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 19 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 @@ -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
@@ -0,0 +1,12 @@
package greencity.exceptions.image;

public class FileIsNullException extends RuntimeException {
/**
* Constructor with message.
*
* @param message message, that explains cause of the exception.
*/
public FileIsNullException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package greencity.exceptions.image;

import greencity.constant.ErrorMessage;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class FileIsNullExceptionTest {
@Test
void fileIsNullExceptionTest() {
String message = "File equals null";
FileIsNullException ex = new FileIsNullException(message);
assertEquals(ErrorMessage.FILE_IS_NULL, ex.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
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.FileIsNullException;
import greencity.exceptions.image.FileNotSavedException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -40,6 +42,9 @@ public AzureCloudStorageService(@Autowired PropertyResolver propertyResolver) {
*/
@Override
public String upload(MultipartFile multipartFile) {
if (multipartFile == null) {
throw new FileIsNullException(ErrorMessage.FILE_IS_NULL);

Choose a reason for hiding this comment

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

please use IllegalArgumentException

Choose a reason for hiding this comment

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

And please add exception handler

}
final String blob = UUID.randomUUID().toString();
BlobClient client = containerClient()
.getBlobClient(blob + multipartFile.getOriginalFilename());
Expand All @@ -65,7 +70,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,111 @@
package greencity.service.ubs;

import com.azure.storage.blob.*;
import greencity.constant.ErrorMessage;
import greencity.exceptions.BadRequestException;
import greencity.exceptions.image.FileIsNullException;
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.mockito.*;

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 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.anyString;
import static org.mockito.Mockito.*;

@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", " ");

Choose a reason for hiding this comment

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

please use some values for properties

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

@Mock
private PropertyResolver propertyResolver;

private AzureCloudStorageService azureCloudStorageService;

@Mock
BlobContainerClient containerClient;

Choose a reason for hiding this comment

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

private


@Mock
BlobClient blobClient;

Choose a reason for hiding this comment

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

private


@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(multipartFile);

Choose a reason for hiding this comment

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

Unnecessary check. multipartFile could not be null
You created it here

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());
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();
}

@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;
FileIsNullException ex =
assertThrows(FileIsNullException.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 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,65 @@
package greencity.service.ubs;

import greencity.ModelUtils;
import greencity.entity.order.Order;
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.glassfish.hk2.utilities.Stub;
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 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.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@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
UserRepository userRepository;

@Mock
UserTableRepo userTableRepo;

@Mock
EmployeeRepository employeeRepository;

@InjectMocks
ValuesForUserTableServiceImpl valuesForUserTableService;

@Test
void getAllFields() {

Choose a reason for hiding this comment

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

please add test if user does not exist

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(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());
}

}
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