简体   繁体   中英

Simple Mockito Unit Test failed

I'm trying to produce a first test with Mockito in a Spring Boot Application.

Here is the complete 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");
    }
}

And here is the error message:

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

As you can see, the test is supposed to pass because I've created a new object and I use the same reference each time!

So, I've the solution. I've made 2 mistakes with the service:

@Mock
private ObjectService objectService;

Here I need the ObjectServiceImpl and not the interface. Than, I've use @InjectMocks instead of @Mock. For the moment, I already don't know what is the difference but it works!

@InjectMocks
private ObjectServiceImpl objectServiceImpl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM