напиши тест
@Service
@Slf4j
public class PreventiveMaintenanceServiceImpl implements PreventiveMaintenanceService {
private static final Long MAINTENANCE_TIME = 3601005L;
private final List<TimeMaintenance> maintenances = new ArrayList<>();
private String preventiveMaintenanceTime;
@Autowired
ErrorMessageService errorMessageService;
@Autowired
TransferPropertyService transferPropertyService;
@Override
public String checkPreventiveMaintenanceProcess() {
LocalDateTime nowCheck = LocalDateTime.now();
for (TimeMaintenance maintenance : maintenances) {
String tag = maintenance.getTag(nowCheck);
if (StringUtils.isNotEmpty(tag)) {
return errorMessageService.getDescriptionCustomer(MAINTENANCE_TIME).replace("${tag}", tag);
}
}
return "";
}
Assistant
User
Assistant
Чтобы написать тест для метода checkPreventiveMaintenanceProcess в классе PreventiveMaintenanceServiceImpl, можно использовать фреймворк для тестирования, такой как JUnit и Mockito для создания заглушек (mocks) для зависимостей.
Вот пример теста для вашего класса:
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDateTime;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class PreventiveMaintenanceServiceImplTest {
@InjectMocks
private PreventiveMaintenanceServiceImpl preventiveMaintenanceService;
@Mock
private ErrorMessageService errorMessageService;
@Mock
private TransferPropertyService transferPropertyService;
@BeforeEach
public void init() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testCheckPreventiveMaintenanceProcessWithEmptyMaintenances() {
// Задаем пустой список для теста
preventiveMaintenanceService.setMaintenances(Collections.emptyList());
String result = preventiveMaintenanceService.checkPreventiveMaintenanceProcess();
// Ожидаем пустую строку, когда maintenances пуст
assertEquals("", result);
}
@Test
public void testCheckPreventiveMaintenanceProcessWithTag() {
LocalDateTime now = LocalDateTime.now();
TimeMaintenance maintenance = mock(TimeMaintenance.class);
// Подготовка возвращаемого значения getTag()
when(maintenance.getTag(now)).thenReturn("TestTag");
preventiveMaintenanceService.setMaintenances(Collections.singletonList(maintenance));
// Подготовка mock для errorMessageService
when(errorMessageService.getDescriptionCustomer(anyLong())).thenReturn("Maintenance error: ${tag}");
String result = preventiveMaintenanceService.checkPreventiveMaintenanceProcess();
// Проверяем, что результат содержит замененное значение тега
assertEquals("Maintenance error: TestTag", result);
}
@Test
public void testCheckPreventiveMaintenanceProcessWithNoTag() {
LocalDateTime now = LocalDateTime.now();
TimeMaintenance maintenance = mock(TimeMaintenance.class);
// Подготовка возвращаемого значения getTag()
when(maintenance.getTag(now)).thenReturn("");
preventiveMaintenanceService.setMaintenances(Collections.singletonList(maintenance));
String result = preventiveMaintenanceService.checkPreventiveMaintenanceProcess();
// Ожидаем пустую строку, когда tag отсутствует
assertEquals("", result);
}
}
Обратите внимание на несколько вещей:
Используются аннотации @InjectMocks и @Mock для инициализации зависимостей.
Метод setMaintenances в PreventiveMaintenanceServiceImpl предполагает, что внутри класса есть метод для установки списка maintenances. Вам нужно будет добавить этот метод, если он отсутствует.
Тесты покрывают различные сценарии работы метода checkPreventiveMaintenanceProcess, включая случаи с пустыми данными, данными с тегами и без тегов.
Этот пример написан на JUnit 5; убедитесь, что ваши зависимости указаны правильно в вашем проекте.
я вот так делаю, в чем проблема?
@Test
void testCheckPreventiveMaintenanceProcessWithEmptyMaintenances() {
String tag = "";
when(StringUtils.isNotEmpty(tag)).thenReturn(false);
String result = preventiveMaintenanceService.checkPreventiveMaintenanceProcess();
assertEquals("", result);
}
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Boolean cannot be returned by toString()
toString() should return String
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
This exception might occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
at acq.micro.acccardtransfer.impl.PreventiveMaintenanceServiceImplTest.testCheckPreventiveMaintenanceProcessWithEmptyMaintenances(PreventiveMaintenanceServiceImplTest.java:38)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChainValidatingInvocation.proceed(InvocationInterceptorChain.java:131)atReflectiveInterceptorCall.lambdaofVoidMethod0(InterceptingExecutableInvoker.java:103)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambdainvoke0(InterceptingExecutableInvoker.java:93)
at org.junit.jupiter.engine.execution.InvocationInterceptorChaininvokeTestMethodexecuteRecursivelyexecuteRecursivelyexecuteRecursivelyexecuteRecursivelyexecuteRecursivelyexecuteRecursivelyexecuteRecursivelyexecuteRecursivelyexecuteRecursivelyexecuteDelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunnerRepeater1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Проблема, с которой вы столкнулись, связана с тем, что вы пытаетесь замокировать статический метод StringUtils.isNotEmpty с использованием Mockito, что не поддерживается стандартным образом.
Ваша попытка сделать when(StringUtils.isNotEmpty(tag)).thenReturn(false); вызывает ошибку, потому что StringUtils — это статический класс, и вы не можете использовать Mockito для мокирования статических методов без дополнительных библиотек, таких как Mockito с поддержкой статических методов (например, PowerMockito).
Кроме того, ваша логика теста не совсем корректна. Метод checkPreventiveMaintenanceProcess проверяет список maintenances, и вам нужно установить его пустым перед вызовом метода.
Вот исправленный пример теста, который следует использовать. Вместо мокирования StringUtils мы просто проверяем, что список maintenances пуст, и вызываем метод checkPreventiveMaintenanceProcess.