weixin_44876820
肖潇晓枭逍
2019-05-29 09:14
采纳率: 42.9%
浏览 1.3k
已采纳

spring boot单元测试时出现NullPointerException怎么解决?

测试类代码

public class ExpressDeliveryControllerTest {
    @Autowired
    private ExpressDeliveryController expressDeliveryController;

    private MockMvc mvc;
    @Before
    public void SetupContext() throws Exception{
        mvc = MockMvcBuilders.standaloneSetup(expressDeliveryController).build();
    }   
    /**
     * 测试getDeliveryLocationByCode方法
     */
    @Test
    public void getDeliveryLocationByCodeTest() throws Exception{


         MultiValueMap<String, Object> map = new LinkedMultiValueMap<String,Object>();
         map.add("shequId", 1); map.add("code", 11111111);


        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post("/delivery/getDeliveryLocation").accept(MediaType.APPLICATION_JSON).param("shequId", "1")).andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
    }
}

控制类代码

    @PostMapping(value = "/delivery/getDeliveryLocation")
    @ResponseBody
    public Map<String, Object> getDeliveryLocationByCode(@Valid @NotNull(message = "社区编号不能为空") String shequId,
            @Valid @NotNull(message = "取货码不能为空") @Length(min = 6, max = 11, message = "请输入正确的取货码") String code) {
        Map<String, Object> map = deliveryService.getDeliveryLocation(shequId, code);
        if (map.isEmpty()) {
            map.put("isError", true);
        } else {
            map.put("isError", false);
            map.put("location", map.get("position"));
        }
        return map;
    }

错误信息

图片说明
test修改后

public class ExpressDeliveryControllerTest {

    private ExpressDeliveryController expressDeliveryController = new ExpressDeliveryController();

    private MockMvc mvc;
    @Before
    public void SetupContext() throws Exception{
        mvc = MockMvcBuilders.standaloneSetup(expressDeliveryController).build();
    }   
    /**
     * 测试getDeliveryLocationByCode方法
     */
    @Test
    public void getDeliveryLocationByCodeTest() throws Exception{

         MultiValueMap<String, String> map = new LinkedMultiValueMap<String,String>();
         map.add("shequId", "1"); map.add("code", "11111");
         ResultActions result =  mvc.perform(MockMvcRequestBuilders.post("/delivery/getDeliveryLocation").params(map));
    }
}

错误信息

图片说明

这个是Controller进入Service层的方法,打印的数据正常

图片说明

这是Service层代码
图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • qq_33427422
    子系天下 2019-05-29 09:20
    已采纳

    报错信息贴一下,方便定位,正常来说,空指针跟是不是Test没有关系

    点赞 评论

相关推荐