0

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)
public @ResponseBody Hospital getHospital(@PathVariable("id") int id) throws Exception {
        Hospital hospital = this.hospitalService.getHospital(id);
        return hospital;
    }

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


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


    return hospitalService.addHospital(hospital);
}

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

return hospitalService.updateHospital(hospital);
}

//@DeleteMapping("deleteHospital")
@RequestMapping(value = "hospitals/", method = RequestMethod.DELETE)
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)

same is thrown for other tests as well but to keep short i am mentioning only 2 of them here

i am not understanding why am i getting this error and what could be reason for it.i tried removing unnecessary imports but yet it could not help me out. i have there is 404 error received instead of 200 and i am not able to understand what could be the reason

4
  • Try removing headers="MediaType.APPLICATION_JSON" from your controller class. Also, why do you need to autowire the same repository class in both the setter and the constructor in the service layer. Keep either one of the autowiring. Commented May 18, 2020 at 5:58
  • retrievetest_ok(com.example.project.HospitalControllerTest) Time elapsed: 0.015 sec <<< FAILURE! java.lang.AssertionError: Status expected:<200> but was:<400> updatehospital_ok(com.example.project.HospitalControllerTest) Time elapsed: 0.006 sec <<< FAILURE! java.lang.AssertionError: Status expected:<200> but was:<400>
    – pravin
    Commented May 25, 2020 at 6:48
  • i removed the headers and autowire still getting this error
    – pravin
    Commented May 25, 2020 at 6:49
  • Also in your test class you have both@SpringBootTest and @RunWith annotations, it you need tk start the application context just use the springbootteat annotation and omit the other one. Commented May 25, 2020 at 13:23

1 Answer 1

1
HospitalController.java
package com.example.project;



import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;




@RestController
@RequestMapping("/test/")
public class HospitalController {

    @Autowired
    private HospitalService hospitalService;

@GetMapping("hospitals/{id}")
public @ResponseBody Hospital getHospital(@PathVariable("id") int id) throws Exception {
 return hospitalService.getHospital(id);


    }

@GetMapping("hospitals/")
public @ResponseBody List<Hospital> getAllHospitals() throws Exception {
return hospitalService.getAllHospitals();

    }


@PostMapping("hospitals/")
public ResponseEntity<String> addHospital(@RequestBody Hospital hospital  ) {
hospitalService.addHospital(hospital);
//URI location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(sevedUser.getId()).toUri();
return new ResponseEntity<>(HttpStatus.OK);
}


public ResponseEntity<String> updateHospital(@RequestBody Hospital hospital) {
hospitalService.updateHospital(hospital);

    return ResponseEntity.ok("ok");
}

@DeleteMapping("hospitals/")
public ResponseEntity<String> deleteHospital(@RequestBody Hospital hospital) {
hospitalService.deleteHospital(hospital);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

}
HospitalService.java
package com.example.project;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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



@Service
public class HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;


public List<Hospital> getAllHospitals(){
    List<Hospital> hos = new ArrayList<Hospital>();
    hospitalRepository.findAll().forEach(hos1 -> hos.add(hos1));
    return hos;
}

public Hospital getHospital(int id){

    return hospitalRepository.findOne(id);
}

public void addHospital(Hospital hospital){
hospitalRepository.save(hospital);
}

public void updateHospital(Hospital hos){
//if(hospitalRepository.findById(hos.getId()).isPresent())
//      {
//  Hospital hospital=hospitalRepository.findById(hos.getId()).get();
//  hospital.setName(hos.getName());
//  hospital.setCity(hos.getCity());
//  hospital.setRating(hos.getRating());
    hospitalRepository.save(hos);

//      }

}

public void deleteHospital(Hospital hospital) {

hospitalRepository.delete(hospital);
}
}
Hospital.java
package com.example.demo.Hospital;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Hospital {

  @Id
 

      public int getId() {
        return id;
    }
    public Hospital() {
    super();
}
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public Hospital(int id, String name, String city, double rating) {
        super();
        this.id = id;
        this.name = name;
        this.city = city;
        this.rating = rating;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public double getRating() {
        return rating;
    }
    public void setRating(double rating) {
        this.rating = rating;
    }
    private int id;
      private String name;
      private String city;
      private double rating;



    }
HospitalRepository.java

package com.example.demo.Hospital;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface HospitalRepository extends JpaRepository<Hospital,Integer>{

}
application.properties
server.port=8080
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:testdb

data.sql

insert into hospital values(1,'John','bihar',22);
1
  • Code-only answers are low quality answers. Commented Oct 8, 2020 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.