Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting autowired bean using Mockito and setting some properties on the mock

Given the following @Component class:

@Component
public class MovieFinderImpl implements MovieFinder {

    @Autowired
    private Movie movie;

    @Override
    public List<Movie> findAll() {      
        List<Movie> movies = new ArrayList<>();
        movies.add(movie);
        return movies;
    }

}

I am trying to learn how to unit test this example component without doing an integration test (so no @RunWith(SpringRunner.class) and @SpringBootTest annotations on the test class).

When my test class looks like this:

public class MovieFinderImplTest {

    @InjectMocks
    private MovieFinderImpl movieFinderImpl;

    @Mock
    public Movie movieMock;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        movieMock.setTitle("test");
        movieMock.setDirector("directorTest");
    }

    @Test
    public void testFindAll() {         
        List<Movie> movies = movieFinderImpl.findAll();
        Assert.assertNotNull(movies.get(0));

        String expectedTitle = "test";
        String actualTitle = movies.get(0).getTitle();
        Assert.assertTrue(String.format("The expected name is %s, but the actual name is %s", expectedTitle, actualTitle), expectedTitle.equals(actualTitle));

        String expectedDirector = "testDirector";
        String actualDirector = movies.get(0).getDirector();
        Assert.assertTrue(String.format("The expected name is %s, but the actual name is %s", expectedDirector, actualDirector), expectedDirector.equals(actualDirector));
    }
}

... the mock is not null, but the mock class variables are and thus:

java.lang.AssertionError: The expected name is test, but the actual name is null

I have browsed through http://www.vogella.com/tutorials/Mockito/article.html , but was unable to find an example of how to set a class variable on a mock.

How do I properly mock the movie object? More in general is this the proper way to test this MovieFinderImp class? My inspiration of just component testing was this blog https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

(ps: I wonder if I should actually test movie.get() method in this test class...perhaps my test design is just wrong).

like image 977
Sander_M Avatar asked Dec 05 '22 17:12

Sander_M


1 Answers

There is a problem with the way you are mocking in a @Before method. Instead of

movieMock.setTitle("test");
movieMock.setDirector("directorTest");

Do it like that

Mockito.when(movieMock.getTitle()).thenReturn("test");
Mockito.when(movieMock.getDirector()).thenReturn("directorTest");
like image 83
marians27 Avatar answered Dec 09 '22 14:12

marians27