Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 获取mvc.perform()的java.lang.NullPointerException_Unit Testing_Spring Boot_Nullpointerexception_Mockito_Mockmvc - Fatal编程技术网

Unit testing 获取mvc.perform()的java.lang.NullPointerException

Unit testing 获取mvc.perform()的java.lang.NullPointerException,unit-testing,spring-boot,nullpointerexception,mockito,mockmvc,Unit Testing,Spring Boot,Nullpointerexception,Mockito,Mockmvc,我不熟悉spring boot中的单元测试。我正在尝试测试一个服务,并使用Mockito进行测试。当我执行mvc.perform()时,我得到一个空值。我使用when()指定要返回的内容。但不知道为什么失败。请提供一些有价值的投入。以下是fe代码片段: @Test public void testAll() throws Exception { /*Mockito.when(sensorDao.findAll()).thenReturn((Iterable<Sensor>)

我不熟悉spring boot中的单元测试。我正在尝试测试一个服务,并使用Mockito进行测试。当我执行mvc.perform()时,我得到一个空值。我使用when()指定要返回的内容。但不知道为什么失败。请提供一些有价值的投入。以下是fe代码片段:

@Test
public void testAll() throws Exception {

    /*Mockito.when(sensorDao.findAll()).thenReturn((Iterable<Sensor>) s2);
    assertEquals(200,expect().statusCode(200));*/

    Collection<Sensor>list =  getEntityListStubData();
    when(sensorserviceimpl.findAll()).thenReturn(list);
    when(sensorService.findAll()).thenReturn(list);
    when(sensorDao.findAll()).thenReturn(list);
    String uri="/sensor";
    //System.out.print("gfnjhkjjhhg");
    System.out.println("Helllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllloooooooooooooooooooooooooooooooooooooooooooo");
    System.out.println(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON));
    MvcResult result = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)).andReturn();
    String content = result.getResponse().getContentAsString();
    int status = result.getResponse().getStatus();
 }
以下是调试结果:


自spring boot以来
1.4.0
您可以使用
@WebMvcTest
自动配置
MockMvc
。另外,使用
@MockBean
模拟控制器中的任何依赖项

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private SensorDao sensorDao;

}

自spring启动以来,您可以使用
@WebMvcTest
自动配置
MockMvc
。另外,使用
@MockBean
模拟控制器中的任何依赖项

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private SensorDao sensorDao;

}

@AutoConfigureMockMvc,也会做这个把戏

@AutoConfigureMockMvc,也会做这个把戏

你的回答给了我一个正确的方向@AutoConfigureMockMvc终于为我工作了。MockMvc需要自动配置。非常感谢。:-)我也是这样,你的回答给了我一个正确的方向@AutoConfigureMockMvc终于为我工作了。MockMvc需要自动配置。非常感谢。:-)对我来说也是如此。