簡體   English   中英

java.lang.AssertionError:預期狀態:<200> 但為:<404> 對於 Spring 啟動 Rest Controller

[英]java.lang.AssertionError: Status expected:<200> but was:<404> for Spring Boot Rest Controller

這是我運行集成測試時的錯誤 class:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /worker/savePaper
       Parameters = {idWorker=[123], workerType=[night], abilities=[{'security'}]}
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"205"]
             Body = {
  "workerEntity" : {
    "idWorker" : "123",
    "isAlive" : true,
    "isWorking" : true,
    "validatePro" : true,
    "validatePen" : true,
    "validateBi" : true
  }
}
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :200
Actual   :404

這是測試 Class:

@RunWith(SpringRunner.class)
@WebMvcTest(WorkerController.class)
public class WorkerControllerIntegrationTest {
    final private String URL_SAVE_PAPER = "/worker/savePaper";

    @MockBean
    IWorkerService workerService;

    @MockBean
    IWorkerAbilititesService workerAbilitiesService;

    @Autowired
    private MockMvc mvc;

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSavePaper() throws Exception {
        PaperFormform = new PaperForm(
                new WorkerEntity());
        form.getWorkerEntity().setIdWorker("123");
        form.getWorkerEntity().setIsAlive(true);
        form.getWorkerEntity().setIsWorking(true);
        form.getWorkerEntity().setValidatePro(true);
        form.getWorkerEntity().setValidatePen(true);
        form.getWorkerEntity().setValidateBi(true);

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        String requestJson=ow.writeValueAsString(form);

        mvc.perform(post(URL_SAVE_PAPER).contentType(APPLICATION_JSON_UTF8)
                .param( "idWorker", "123")
                .param("workerType", "night")
                .param("abilitities", "{'security'}")
                .content(requestJson))
                .andExpect(status().isOk())
        .andReturn();
    }

}

我的Object:

import lombok.*;

import javax.persistence.*;

@Entity
@Data
@Table(name = "worker")
@AllArgsConstructor
@NoArgsConstructor
public class WorkerEntity implements java.io.Serializable {

    @Id
    @Column(name = "id_worker")
    private String idWorker;

    @Column(name = "is_alive")
    private boolean isAlive;

    @Column(name = "is_working")
    private boolean isWorking;

    @Column(name = "validate_pro")
    private Boolean ValidatePro;

    @Column(name = "validate_pen")
    private Boolean validatePen;

    @Column(name = "validate_bi")
    private Boolean validateBi;
}

我的映射 Class 與前面:(我通過表格接收數據)

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.app.entity.WorkerEntity;
import lombok.AllArgsConstructor;
import lombok.Data;

import javax.validation.constraints.NotNull;

@JsonDeserialize(as = WorkerEntity.class)
@AllArgsConstructor
@Data
public class paperForm {
    @NotNull
    private WorkerEntity workerEntity;
}

我的Controller:

@RestController
@RequestMapping(value = "worker")
@RequiredArgsConstructor
public class WorkerController {

    @Autowired
    private IWorkerService workerService;

    @Autowired
    private IWorkAbilitiesService workAbilitiesService;

    @PostMapping(value = "savePaper")
    @ResponseBody
    @RequestMapping(consumes="application/json",
            produces="application/json")
    public ResponseEntity<WorkerEntity> savePaper(@Valid @RequestBody final PaperForm form, @RequestParam final String idWorker, @RequestHeader("workerType") String workerType,
                                                          @RequestHeader(required = false, value = "Abilities") String[] abilities) {

        HttpStatus statut = HttpStatus.FORBIDDEN;
        WorkerEntity entity = null;

        if (workAbilitiesService.validateAbilities(abilities, idWorker, workerType)) {
            final WorkerEntity w =orkerEntity new WorkerEntity();
            if (workerEntity.getValidatePro() && workerEntity.getValidatePen() && workerEntity.getValidateBI()) {
                workerEntity.setIsAlive(form.getWorkerEntity().isAlive());
                workerEntity.setIsWorking(form.getWorkerEntity().isWorking());
                status = HttpStatus.OK;
                entity = this.workerService.savePaper(workerEntity);
            }
        }
        return ResponseEntity.status(statut).body(entity);
    }
}

我的服務:

@Transactional
@Service
public class WorkerServiceImpl implements IWorkerService {

    @Autowired
    private IWorkerRepository workerRepository;
}

起初我有幾天都是 415 狀態,我無法重新愛它,但我知道如何設法通過它,現在我有一個 404 失敗狀態。

您缺少/ ,因此找不到 404。 它應該是@RequestMapping(value = "/worker")

@PostMapping(value = "/savePaper")為了形成/worker/savePaper

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM