简单的 Mockito 单元测试失败

Simple Mockito Unit Test failed

我正在尝试在 Spring 启动应用程序中使用 Mockito 进行首次测试。

这是完整的 class:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Optional;

import static org.mockito.Mockito.doReturn;

@ExtendWith(MockitoExtension.class)
public class ObjectServiceTest {

    @Mock
    private ObjectRepository objectRepository;

    @Mock
    private ObjectService objectService;

    @Test
    @DisplayName("Should find object by objNumero with its service")
    void shouldFindObjectByObjNumero() {

        Object object = new Object("00000271");

        doReturn(Optional.of(object)).when(objectRepository).findObjectByObjNumero("00000271");

        Optional<Object> returnedObject = objectService.findObjectByObjNumero("00000271");

        Assertions.assertTrue(returnedObject.isPresent(), "Object was found");
        Assertions.assertSame(returnedObject.get(), object, "The returned object wasn't the same as the mock");
    }
}

这是错误消息:

org.opentest4j.AssertionFailedError: Object was not found ==> Expected :true Actual :false

如您所见,测试应该会通过,因为我创建了一个新对象并且每次都使用相同的引用!

所以,我找到了解决方案。我在服务中犯了 2 个错误:

@Mock
private ObjectService objectService;

这里我需要 ObjectServiceImpl 而不是接口。比起,我使用@InjectMocks 而不是@Mock。目前,我还不知道有什么区别,但它确实有效!

@InjectMocks
private ObjectServiceImpl objectServiceImpl;