Greg
Greg

Reputation: 126

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!

Upvotes: 0

Views: 393

Answers (1)

Greg
Greg

Reputation: 126

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;

Upvotes: 1

Related Questions