java.lang.AssertionError:预期状态:<200>,但状态为:<404>,且测试用例失败

i wrote the following code and test cases has to be passed ... iam thrown "java.lang.AssertionError: Status expected:<200> but was:<404> " error please help out

**controller** this is the controller class 

package com.example.project;
import com.example.project.HospitalService;
import com.example.project.Hospital;
import java.util.List;
import java.lang.*;
import org.springframework.http.ResponseEntity;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.DeleteMapping;
//import org.springframework.web.bind.annotation.PutMapping;
//import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@RestController
@RequestMapping("/test/")
public class HospitalController {

    @Autowired
    private HospitalService hospitalService;


@RequestMapping(value = "hospitals/{id}", method = RequestMethod.GET/*,produces="MediaType.APPLICATION_JSON"*/,headers="MediaType.APPLICATION_JSON")
public @ResponseBody Hospital getHospital(@PathVariable("id") int id) throws Exception {
        Hospital hospital = this.hospitalService.getHospital(id);
        return hospital;
    }

@RequestMapping(value = "hospitals/", method = RequestMethod.GET/*,produces="MediaType.APPLICATION_JSON"*/)
public @ResponseBody List<Hospital> getAllHospitals() throws Exception {
        return this.hospitalService.getAllHospitals();
    }


//@PostMapping("addHospital")
@RequestMapping(value = "hospitals/", method = RequestMethod.POST,headers="MediaType.APPLICATION_JSON")
public ResponseEntity<String> addHospital(@RequestBody Hospital hospital  ) {


    return hospitalService.addHospital(hospital);
}

//@PutMapping("updateHospital")
@RequestMapping(value = "hospitals/", method = RequestMethod.PUT,headers="MediaType.APPLICATION_JSON"/*,produces="MediaType.APPLICATION_JSON"*/)
public ResponseEntity<String> updateHospital(@RequestBody Hospital hospital) {

return hospitalService.updateHospital(hospital);
}

//@DeleteMapping("deleteHospital")
@RequestMapping(value = "hospitals/", method = RequestMethod.DELETE,headers="MediaType.APPLICATION_JSON")
public ResponseEntity<String> deleteHospital(@RequestBody Hospital hospital) {

 return hospitalService.deleteHospital(hospital);
}

}


**service** : the below is the service class 

package com.example.project;
import  com.example.project.Hospital;
import org.springframework.http.ResponseEntity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
import java.lang.*;
import java.util.List;
import  com.example.project.HospitalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatus;




@Service
public class HospitalService extends Exception{

    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    public HospitalService(HospitalRepository hospitalRepository){
      this.hospitalRepository=hospitalRepository;
    }
public List<Hospital> getAllHospitals(){
List<Hospital> x= (List)hospitalRepository.findAll();
return x;
}

public Hospital getHospital(int id){
  Hospital x= hospitalRepository.findById(id);
    return x;
}

public ResponseEntity<String> addHospital(Hospital hospital){
 try{

  Hospital h =hospitalRepository.save(hospital);

   return new ResponseEntity<>(HttpStatus.OK);
 }
catch(Exception e){

 return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}

}

public ResponseEntity<String> updateHospital(Hospital hospital){
 try{
  Hospital h = (hospitalRepository.save(hospital));

   return new ResponseEntity<>(HttpStatus.OK);
 }
catch(Exception e){

return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}

 }

public ResponseEntity<String> deleteHospital(Hospital hospital) {
  try {
   hospitalRepository.delete(hospital);

   return new ResponseEntity<>(HttpStatus.NO_CONTENT);
  }
  catch(Exception e){

 return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
}


}



**Test cases** the following is test class which needs to be passed for above given service and controller 

package com.example.project;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.databind.ObjectMapper;



@SpringBootTest
@RunWith(SpringRunner.class)
public class HospitalControllerTest {


    private MockMvc mockMvc;

    @Autowired
    WebApplicationContext context;



    @Before
    public void setup() {
        //this.mockMvc = MockMvcBuilders.standaloneSetup(new WeatherApiController()).build();
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }


    @Test
    public void retrievetestok() throws Exception {
        addhospitalok();
         mockMvc.perform(get("/test/hospitals/1000" )).andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1000))
                    .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Apollo Hospital"))
                    .andExpect(MockMvcResultMatchers.jsonPath("$.rating").value(3.8))
                    .andExpect(MockMvcResultMatchers.jsonPath("$.city").value("Chennai"));

    }


    @Test
    public void addhospitalok() throws Exception {
        Hospital hosp=new Hospital();
        hosp.setId(1000);
        hosp.setName("Apollo Hospital");
        hosp.setCity("Chennai");
        hosp.setRating(3.8);
        byte[] hospJson = toJson(hosp);
        Hospital hosp1=new Hospital();
        hosp1.setId(1001);
        hosp1.setName("Global Hospital");
        hosp1.setCity("Bangalore");
        hosp1.setRating(3.5);
        byte[] hospJson1 = toJson(hosp1);
         mockMvc.perform(post("/test/hospitals/" )//.andDo(print())
                    .content(hospJson)
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk());
         mockMvc.perform(post("/test/hospitals/" )//.andDo(print())
                    .content(hospJson1)
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk());          
    }

    @Test
    public void updatehospitalok() throws Exception {
        Hospital hosp1=new Hospital();
        hosp1.setId(1001);
        hosp1.setName("Global Hospitals");
        hosp1.setCity("Goa");
        hosp1.setRating(3.5);
        byte[] hospJson1 = toJson(hosp1);
         mockMvc.perform(post("/test/hospitals/" )//.andDo(print())
                    .content(hospJson1)
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk());          

         mockMvc.perform(get("/test/hospitals/1001" )).andDo(print())
         .andExpect(status().isOk())
         .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Global Hospitals"))
         .andExpect(MockMvcResultMatchers.jsonPath("$.city").value("Goa"));
    }


    @Test
    public void deleteHospitalok() throws Exception {
        Hospital hosp=new Hospital();
        hosp.setId(1000);
        hosp.setName("Apollo Hospital");
        hosp.setCity("Chennai");
        hosp.setRating(3.8);
        byte[] hospJson = toJson(hosp);
        mockMvc.perform(delete("/test/hospitals/" )//.andDo(print())
                .content(hospJson)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isNoContent());

    }

     private byte[] toJson(Object r) throws Exception {
            ObjectMapper map = new ObjectMapper();
            return map.writeValueAsString(r).getBytes();
        }
}




**ERROR THROWN** this is the error which is thrown by the ide and it doesnt show any compilation or initialization error

-------------------------------------------------------------------------------
Test set: com.example.project.HospitalControllerTest
-------------------------------------------------------------------------------
Tests run: 4, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 10.718 sec <<< FAILURE! - in com.example.project.HospitalControllerTest
addhospitalok(com.example.project.HospitalControllerTest)  Time elapsed: 0.257 sec  <<< FAILURE!
java.lang.AssertionError: Status expected:<200> but was:<404>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.example.project.HospitalControllerTest.addhospitalok(HospitalControllerTest.java:75)

deleteHospitalok(com.example.project.HospitalControllerTest)  Time elapsed: 0.02 sec  <<< FAILURE!
java.lang.AssertionError: Status expected:<204> but was:<404>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.example.project.HospitalControllerTest.deleteHospitalok(HospitalControllerTest.java:116)

其他测试也一样,但是为了简短起见,我在这里只提到其中的两个

我不明白为什么会收到此错误以及可能是该错误的原因。我尝试删除了不必要的导入,但仍然无法解决问题。我收到的是404错误而不是200错误,我无法理解可能是什么原因

评论