如何将@WebMvcTest 用于单元测试 POST 方法?

我正在使用 Spring Boot 和 Mockito 运行单元测试,我正在测试 RESTful 服务。当我尝试测试 GET 方法时,它成功运行,但是当我尝试测试 POST 方法时,它失败了。我应该怎么做才能解决这个问题?提前致谢!


这是 REST 控制器的代码:


package com.dgs.restfultesting.controller;


import java.net.URI;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.servlet.support.ServletUriComponentsBuilder;


import com.dgs.restfultesting.business.ItemBusinessService;

import com.dgs.restfultesting.model.Item;


@RestController

public class ItemController {


    @Autowired

    private ItemBusinessService businessService;


    @GetMapping("/all-items-from-database")

    public List<Item> retrieveAllItems() {

        return businessService.retrieveAllItems(); 

    }


    @PostMapping("/items")

    public Item addItem(@RequestBody Item item) {

        Item savedItem = businessService.addAnItem(item); 


        return savedItem;

    }

}

业务层:


package com.dgs.restfultesting.business;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;


import com.dgs.restfultesting.data.ItemRepository;

import com.dgs.restfultesting.model.Item;


@Component

public class ItemBusinessService {


    @Autowired

    private ItemRepository repository;


    public Item retrieveHardcodedItem() {

        return new Item(1, "Book", 10, 100); 

    }


    public List<Item> retrieveAllItems() {


        List<Item> items = repository.findAll(); 


        for (Item item : items) {

            item.setValue(item.getPrice() * item.getQuantity());  

        }


        return items;  

    }


    public Item addAnItem(Item item) {

        return repository.save(item); 

    }

}


不负相思意
浏览 210回答 1
1回答

MMMHUHU

从您的控制器返回 201:正如您的断言测试期望201使用created状态一样,但您的控制器返回 200(OK)。&nbsp; &nbsp;@PostMapping("/items")&nbsp; &nbsp; public ResponseEntity<?> addItem(@RequestBody Item item) {&nbsp; &nbsp; &nbsp; &nbsp; Item savedItem = itemBusinessService.addAnItem(item);&nbsp; &nbsp; &nbsp; &nbsp; return new ResponseEntity<>(savedItem, HttpStatus.CREATED);&nbsp; &nbsp; }或者修改您的测试以检查状态 OK(200)。如果您不想断言“位置”,请更新您的测试。&nbsp;@Test&nbsp;public void createItem() throws Exception {&nbsp;RequestBuilder request = MockMvcRequestBuilders&nbsp; &nbsp; &nbsp; &nbsp; .post("/items")&nbsp; &nbsp; &nbsp; &nbsp; .accept(MediaType.APPLICATION_JSON)&nbsp; &nbsp; &nbsp; &nbsp; .content("{\"id\":1,\"name\":\"Book\",\"price\":10,\"quantity\":100}")&nbsp; &nbsp; &nbsp; &nbsp; .contentType(MediaType.APPLICATION_JSON);MvcResult result = mockMvc.perform(request)&nbsp; &nbsp; &nbsp; &nbsp; .andExpect(status().isOk()).andReturn();}更新--允许位置标头作为响应如果您希望“位置”从标题返回,请修改您的控制器和下面的测试用例以在标题中检查位置。第 1 步:在您的控制器的 add item 方法中,添加位置 uri 并返回。&nbsp;@PostMapping("/items")&nbsp; &nbsp; public ResponseEntity<?> addItem(@RequestBody Item item) {&nbsp; &nbsp; &nbsp; &nbsp; Item savedItem = businessService.addAnItem(item);&nbsp; &nbsp; &nbsp; &nbsp; HttpHeaders httpHeaders = new HttpHeaders();&nbsp; &nbsp; &nbsp; &nbsp; UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.newInstance();&nbsp; &nbsp; &nbsp; &nbsp; UriComponents uriComponents =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uriComponentsBuilder.path("/item/").buildAndExpand("/item/");&nbsp; &nbsp; &nbsp; &nbsp; httpHeaders.setLocation(uriComponents.toUri());&nbsp; &nbsp; &nbsp; &nbsp; return new ResponseEntity<>(savedItem, httpHeaders, HttpStatus.CREATED);&nbsp; &nbsp; }第 2 步:现在您的测试将"location"按照您的预期进行断言。&nbsp;@Test&nbsp; &nbsp; public void createItem() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; RequestBuilder request = MockMvcRequestBuilders&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .post("/items")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .accept(MediaType.APPLICATION_JSON)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .content("{\"id\":1,\"name\":\"Book\",\"price\":10,\"quantity\":100}")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .contentType(MediaType.APPLICATION_JSON);&nbsp; &nbsp; &nbsp; &nbsp; MvcResult result = mockMvc.perform(request)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .andExpect(status().isCreated())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .andExpect(header().string("location", containsString("/item/")))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .andReturn();&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java