class java.lang.Object не может быть преобразован в класс Task при имитации Spring Repository с помощью MockK

2

У меня есть довольно простой модульный тест репозитория Spring для моей Taskсущности.

Вот как настроен репозиторий:

@Repository
interface TaskRepository : CrudRepository<Task, Long>

Вот логика, которую я хотел бы проверить:

// TaskService.kt
    fun deleteSubTask(parentTask: Task, subTask: Task) {
        taskRepository.save(parentTask)
        parentTask.subTasks?.remove(subTask)
        taskRepository.delete(subTask)
    }

и вот мой модульный тест (с JUnit5 и Mockk):

//TaskServiceTest.kt

internal class TaskServiceTest {
    private val taskRepository: TaskRepository = mockk(relaxed = true)
    private val taskService = TaskService(mockk(relaxed = true), taskRepository)

    @Test
    fun `should remove subtask of parent task`() {
        val subTask: Task = mockk()
        val parentTask: Task = mockk()

        taskService.deleteSubTask(parentTask, subTask)

        verify { parentTask.subTasks?.remove(subTask) }
        verify { taskRepository.delete(subTask) }
        verify { taskRepository.save(parentTask) }
    }
}

При выполнении теста появляется следующая ошибка:

22:48:51.245 [Test worker] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for TaskRepository name=#1
22:48:51.483 [Test worker] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for UserRepository name=#2
22:48:51.508 [Test worker] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Task name=#3
22:48:51.552 [Test worker] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Task name=#4
22:48:51.853 [Test worker] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Any name=child of #1#5
22:48:51.888 [Test worker] DEBUG io.mockk.impl.recording.states.AnsweringState - Answering Any(child of #1#5) on TaskRepository(#1).save(Task(#4))

class java.lang.Object cannot be cast to class com.imhotep.backend.domain.model.dao.Task (java.lang.Object is in module java.base of loader 'bootstrap'; com.imhotep.backend.domain.model.dao.Task is in unnamed module of loader 'app')
java.lang.ClassCastException: class java.lang.Object cannot be cast to class com.imhotep.backend.domain.model.dao.Task (java.lang.Object is in module java.base of loader 'bootstrap'; com.imhotep.backend.domain.model.dao.Task is in unnamed module of loader 'app')
    at com.imhotep.backend.repository.TaskRepository$Subclass0.save(Unknown Source)
    at com.imhotep.backend.repository.TaskRepository$Subclass0.save(Unknown Source)
    at com.imhotep.backend.service.TaskService.deleteSubTask(TaskService.kt:54)
    at com.imhotep.backend.service.TaskServiceTest.should remove subtask of parent task(TaskServiceTest.kt:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:135)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:831)

Я понятия не имею, почему taskRepository.delete(subTask)работает, а taskRepository.save(parentTask)тест не проходит с опубликованной ошибкой?

5
  • Обычно вы не должны имитировать значения данных , только объекты с поведением . Это ненормально, что ваши Taskобъекты являются издевательствами; они должны быть настоящими POJO (POKO?). 2 дня назад
  • хорошо, я могу утверждать, что Taskимеет "поведение" удаления subTasksэлементов. Поэтому я издеваюсь над ним - чтобы посмотреть, правильно ли называется этот метод.
    xetra11
    2 дня назад
  • Да, согласен @ chrylis-cautiouslyoptimistic- Я бы не стал писать тест. Проблема в том, что вам нужно ввести mockk call thoval task = mockk<Task>()
    DCTID
    2 дня назад
  • Я понимаю что ты имеешь ввиду. Однако создание простой имитации этих аргументов вместо создания всего экземпляра с конструктором кажется мне проще, поскольку мне просто нужно посмотреть, используются ли они в TaskRepositoryфункциях. Я несколько думаю, что это нормально, не так ли?
    xetra11
    2 дня назад
  • @DCTID, к сожалению, не работает с типизированным вызовом mockk. В Kotlin, насколько мне известно, вывода типа должно быть достаточно.
    xetra11
    2 дня назад
1

Похоже, что возникшая ошибка была вызвана тем, что я объявил TaskRepositoryмакет как relaxed. При объявлении только void-функций (возвращающих Unit в Kotlin ) для ослабления это сработало.

Вот рабочий юнит-тест:

internal class TaskServiceTest {
    private val taskRepository: TaskRepository = mockk(relaxUnitFun = true) // changed from relaxed to relaxUnitFun
    private val taskService = TaskService(mockk(relaxed = true), taskRepository)

    @Test
    fun `should remove subtask of parent task`() {
        val subTask: Task = mockk()
        val parentTask: Task = mockk() {
            every { subTasks } returns mutableListOf(subTask)
        }

        every { taskRepository.save(any()) } returns mockk()

        taskService.deleteSubTask(parentTask, subTask)

        verify { parentTask.subTasks?.remove(subTask) }
        verify { taskRepository.delete(subTask) }
        verify { taskRepository.save(parentTask) }
    }
}