java – 使用Mockito注入autowired bean并在mock上设置一些属性

给定以下@Component类:

@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;
    }

}

我正在尝试学习如何在不进行集成测试的情况下对此示例组件进行单元测试(因此测试类上没有@RunWith(SpringRunner.class)和@SpringBootTest注释).

当我的测试类看起来像这样:

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));
    }
}

… mock不是null,但mock类变量是因此:

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

我浏览过http://www.vogella.com/tutorials/Mockito/article.html,但无法找到如何在模拟上设置类变量的示例.

如何正确模拟电影对象?更一般的是,这是测试这个MovieFinderImp类的正确方法吗?我对组件测试的灵感来自于这个博客https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

(ps:我想知道我是否应该在这个测试类中测试movie.get()方法……也许我的测试设计是错误的).

解决方法:

您在@Before方法中进行模拟的方式存在问题.代替

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

这样做

Mockito.when(movieMock.getTitle()).thenReturn("test");
Mockito.when(movieMock.getDirector()).thenReturn("directorTest");
上一篇:java – 模拟Spring Bean


下一篇:java – 如何确保模拟对象在mockito中只被调用一次