Mockito thenReturn()返回null值

3

我是Mockito的新手,我在使用thenReturn方法时遇到了问题。我阅读了教程,在这种解决方案中运作良好,但在我的程序中与前面的示例存在任何不一致。

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest(value = MovieRestApiController.class, secure = false)
    public class MovieRestApiControllerTest {

            @Autowired
            private MockMvc mockMvc;

            @MockBean
            private MovieService movieService;

            private ArrayList<Movie> moviesMock;

            @Before
            public void setUp() {
                moviesMock = new ArrayList<>(Arrays.asList(new Movie("Top Gun", "Akcja", "Tony Scott", 15000000, 110)));
            }

            String exampleMovieJson = "{\"title\":\"Top Gun\",\"director\":\"Tony Scott\",\"runtime\":\"110\":\"budget\":\"15000000\":\"genre:\":\"Akcja\"}";

            @Test
            public void retrieveDetailsForMovie() throws Exception {
        //THIS FUNCTION CAUSE NULL POINTER EXCEPTION
                Mockito.when(
                        movieService.findMovies(Mockito.anyString(), Mockito.anyString())).thenReturn(moviesMock);

                RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                        "/find-movie").accept(
                        MediaType.APPLICATION_JSON);

                MvcResult result = mockMvc.perform(requestBuilder).andReturn();

                System.out.println(result.getResponse());
                String expected = "{title:Top Gun,director:Tony Scott,runtime:110,budget:15000000,genre:Akcja}";

                JSONAssert.assertEquals(expected, result.getResponse()
                        .getContentAsString(), false);
            }

        }

3
你是否在类上使用了 @RunWith(MockitoJUnitRunner.class) 注解? - SeverityOne
Mock、MockBean和Mockito Mock之间的区别。在代码中初始化模拟对象,或者使用.MockitoJUnitRunner运行。 - Alan Hay
我使用 @RunWith(SpringJUnit4ClassRunner.class)。 - senham
这意味着您的模拟对象从未被初始化,因此保持为“null”。因此,会出现“NullPointerException”。 - SeverityOne
我已经添加了注释,但问题仍然存在。 - senham
1个回答

1

在使用MockMvc进行单元测试时,我曾尝试过将Mockito和Spring注解混合使用,但效果并不理想。下面是我采用的一种方法,可以让Mockito、Spring和MockMvc都能够愉快地工作。当然,如果有更好的建议,我也很乐意听取。

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class MovieRestApiControllerTest {

  // provide a static spring config for this test:
  static class ContextConfiguration {

    // provide Beans that return a Mockito mock object
    @Bean
    public MovieService movieService() {
      return Mockito.mock(MovieService.class);
    }

    ...

  }
    @Autowired
    private MockMvc mockMvc;

    // Autowire your mocks
    @Autowired
    private MovieService movieService;

    private ArrayList<Movie> moviesMock;

    @Before
    public void setUp() {
        moviesMock = new ArrayList<>(Arrays.asList(new Movie("Top Gun", "Akcja", "Tony Scott", 15000000, 110)));
    }

    String exampleMovieJson = "{\"title\":\"Top Gun\",\"director\":\"Tony Scott\",\"runtime\":\"110\":\"budget\":\"15000000\":\"genre:\":\"Akcja\"}";

    // make sure your context is loaded correctly
    @Test
    public void testContextLoaded() {
        assertNotNull(movieService);
    }

    @Test
    public void retrieveDetailsForMovie() throws Exception {
    //THIS FUNCTION CAUSE NULL POINTER EXCEPTION
        Mockito.when(
                movieService.findMovies(Mockito.anyString(), Mockito.anyString())).thenReturn(moviesMock);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                "/find-movie").accept(
                MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        System.out.println(result.getResponse());
        String expected = "{title:Top Gun,director:Tony Scott,runtime:110,budget:15000000,genre:Akcja}";

        JSONAssert.assertEquals(expected, result.getResponse()
                .getContentAsString(), false);
    }

}

抱歉,它对我不起作用,@Autowired 存在问题:“无法自动装配。找不到'MockMvc'类型的bean”。 - senham
你不需要使用Autowire mockMvc - 使用MockMvcBuilders类来提供一个。另外 - 你要测试哪个Controller类?我在你的测试类中没有看到一个。例如:mockMvc = MockMvcBuilders.standaLoneSetup(ControllerUnderTest.class).defaultRequest(get("/findMovie")).build(); - Michael Peacock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接