在SpringBoot中使用Mockmvc perform()方法调用RestController时出现空指针异常

时间:2018-09-22 14:59:12

标签: spring-boot junit spring-restcontroller spring-boot-test

我将MockMvc用于第一种类型。我正在做的是在SPringboot中测试Restcontroller。

我有一个这样的Restcontroller

    @RequestMapping("/address")
    public class AddressController {

    @RequestMapping("/createAddress")
        public Address craeteAddress(Address address)
        {
            Address add=addressService.createAdd(address);
            return add;
        }

@RequestMapping("/getAll")
    public List<Address> getAll()
    {
        return addressService.getAll();

    }




    }

现在我的测试课看起来像这样,

public class AddressControllerTest {

    AddressService addressService = mock(AddressService.class);

    @Autowired
    MockMvc mockMvc;

    private static final String ADDRESS_DTO_JSON =
            "{" +
            "\"id\":\"123\"," +
            "\"pacsId\":\"345\"," +
            "}";

    List<Object> object = new ArrayList<Object>();


        @Before
        public void setup() {


        }

    @Test       
    public void createAddressTest() throws Exception {

        //System.out.println("The Json Content :" + ADDRESS_DTO_JSON);
        this.mockMvc
        .perform(get("address/getAll"))
        .andExpect(status().isOk())
        .andReturn();       
    }

}

我试图在restcontroller中调用'address / getAll'方法。当我运行junit方法时,它在.perform(get(“ address / getAll”))行附近显示“空指针异常”。

我做了一些研究,但没有解决。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我认为您配置了错误的测试课。 尝试这样的事情:

@RunWith(SpringRunner.class)
@WebMvcTest(AddressController.class)
public class AddressControllerTest {
  @Autowired
  MockMvc mockMvc;
}