简体   繁体   中英

Mocked method return value is null in Spring Boot @WebMvcTest

The below test fails with: org.json.JSONException: Unparsable JSON string . I tried various variations of the mocking the saveAndFlush method

//      doAnswer(returnsFirstArg()).when(this.shipwreckRepository).saveAndFlush(shipwreck);

//      when(this.shipwreckRepository.saveAndFlush(shipwreck))
//          .then(returnsFirstArg());

however, the same error pops and MockHttpServletResponse body is null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 

How to mock repository saveAndFlush method return value correctly?

SpringBootHomeControllerTest.java

@RunWith(SpringRunner.class)
@WebMvcTest(ShipwreckController.class)
public class SpringBootShipwreckControllerTests {

@Autowired 
private MockMvc mvc;

@MockBean
private ShipwreckRepository shipwreckRepository;


@Test
public void createShipwreck() throws Exception {
    Shipwreck shipwreck = generateSampleShipwreck();

    when(shipwreckRepository.saveAndFlush(shipwreck)).then(i -> i.getArgumentAt(0, Shipwreck.class));

    ObjectMapper mapper = new ObjectMapper();       
    String shipwreckJson = mapper.writeValueAsString(shipwreck);
    this.mvc.perform(post("/api/v1/shipwrecks")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(shipwreckJson)
                     )

            .andExpect(status().isOk())
            .andExpect(content().json(shipwreckJson));
    verify(this.shipwreckRepository).saveAndFlush(shipwreck);


}

private Shipwreck generateSampleShipwreck() {
    Integer depth = 10;
    Double latitude = 1.0;
    Double longitude = 1.0;
    Integer yearDiscovered = 1;
    String name = "name";
    String description = "desc";
    String condition = "cond";
    Shipwreck shipwreck = new Shipwreck(1L, name, description, condition, depth, latitude, longitude, yearDiscovered);
    return shipwreck;
}

}

ShipwreckRepository.java

public interface ShipwreckRepository extends JpaRepository<Shipwreck, Long> {

}

ShipwreckController.java

@RestController
@RequestMapping("/api/v1/")
public class ShipwreckController {

    @Autowired
    private ShipwreckRepository shipwreckRepository;

    @RequestMapping(value = "shipwrecks", method = RequestMethod.POST)
    public Shipwreck create(@RequestBody Shipwreck shipwreck) {
        return shipwreckRepository.saveAndFlush(shipwreck);
    }
}

Shipwreck.java

package com.boot.model;

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

@Entity
public class Shipwreck {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    String name;
    String description;
    String condition;
    Integer depth;
    Double latitude;
    Double longitude;
    Integer yearDiscovered;

    public Shipwreck() { }

    public Shipwreck(Long id, String name, String description, String condition, Integer depth, Double latitude, Double longitude, Integer yearDiscovered) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.condition = condition;
        this.depth = depth;
        this.latitude = latitude;
        this.longitude = longitude;
        this.yearDiscovered = yearDiscovered;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public Integer getDepth() {
        return depth;
    }

    public void setDepth(Integer depth) {
        this.depth = depth;
    }

    public Double getLatitude() {
        return latitude;
    }

    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }

    public Double getLongitude() {
        return longitude;
    }

    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }

    public Integer getYearDiscovered() {
        return yearDiscovered;
    }

    public void setYearDiscovered(Integer yearDiscovered) {
        this.yearDiscovered = yearDiscovered;
    }
}

Use Mockito.any() rather than a specific instance of Shipwreck in your when() and verify() instructions.

The Shipwreck instance that will be received by your tested controller won't be the instance you created, but a new one built from de-serializing the json you call it with. Therefore, Mockito won't respond to instructions that tell to use the former instance.

Alternative: define appropriate equals() and hashCode() methods for Shipwreck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM