Java 当单元测试控制器i';我得到一个断言错误

Java 当单元测试控制器i';我得到一个断言错误,java,spring-boot,unit-testing,Java,Spring Boot,Unit Testing,我已经用spring boot创建了一个基本的CRUD api。我已经为controller类编写了测试用例,但是在运行测试时出现了错误。 我尝试的代码如下所示 型号 package com.example.crudrestapi.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.p

我已经用spring boot创建了一个基本的CRUD api。我已经为controller类编写了测试用例,但是在运行测试时出现了错误。 我尝试的代码如下所示

型号

package com.example.crudrestapi.model;


import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

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

@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Customer {

    @Id
    @GeneratedValue private Long id;
    private String name;
    private String address;
    private String phoneNumber;
    private String gstin;
    private float outstandingBalance;
}
积垢控制器

public class CrudController {

    @Autowired
    CustomerRepo customerRepo;
     @PostMapping("/customers")
    public @ResponseBody
    Customer postCustomer(@RequestBody Customer customer) {
        return customerRepo.save(customer);

    }


    @PutMapping("customers/{customerId}")
    public ResponseEntity<Customer> updateCustomer(@RequestBody Customer newCustomer, @PathVariable Long customerId) {

        Optional<Customer> optionalCustomer = customerRepo.findById(customerId);
        if (optionalCustomer.isPresent()){
            Customer c = optionalCustomer.get();
            if (newCustomer.getName() != null)
                c.setName(newCustomer.getName());
            if (newCustomer.getGstin() != null)
                c.setGstin(newCustomer.getGstin());
            if (newCustomer.getPhoneNumber() != null)
                c.setPhoneNumber(newCustomer.getPhoneNumber());
            if (newCustomer.getAddress() != null)
                c.setAddress(newCustomer.getAddress());
            if (newCustomer.getOutstandingBalance() != 0.0f)
                c.setOutstandingBalance(newCustomer.getOutstandingBalance());
            return new ResponseEntity<>(customerRepo.save(c), HttpStatus.OK);
        }else{
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("customers/{customerId}")
    public String deleteCustomer(@PathVariable Long customerId) throws ResourceNotFoundException {
        return customerRepo.findById(customerId)
                .map(customer -> {
                    customerRepo.delete(customer);
                    return "Success";
                })
                .orElseThrow(() -> new ResourceNotFoundException());
    }
}
api测试后我得到的错误


我认为问题在于考试。特别是,您在主体中发送信息的方式,因为您发送了一个对象,但MockMvc需要一个JSON格式的字符串来模拟来自API外部的真实请求

解决此问题的方法是:

   @Test
    void postCustomer() throws Exception {
        Customer customer = Customer.builder().name("name").address("address").build();
        given(customerRepo.save(customer));
        mockMvc.perform(post("/customers")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(customer))//Call to other method to transform an object to a JSON
                )
                .andExpect(status().isOk());
    }

    private String asJsonString(final Object obj) {
        try {
            return new ObjectMapper().writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

ObjectMapper来自此包com.fasterxml.jackson.databind.ObjectMapper

我尝试了代码,但出现了错误。我在上面添加了错误,你能检查一下吗。问题是你没有把存根需要做的事情放进去。此行“给定(customerRepo.save(customer));”需要操作.wllReturn(xxxx);谢谢,这就解决了问题
public class CrudController {

    @Autowired
    CustomerRepo customerRepo;
     @PostMapping("/customers")
    public @ResponseBody
    Customer postCustomer(@RequestBody Customer customer) {
        return customerRepo.save(customer);

    }


    @PutMapping("customers/{customerId}")
    public ResponseEntity<Customer> updateCustomer(@RequestBody Customer newCustomer, @PathVariable Long customerId) {

        Optional<Customer> optionalCustomer = customerRepo.findById(customerId);
        if (optionalCustomer.isPresent()){
            Customer c = optionalCustomer.get();
            if (newCustomer.getName() != null)
                c.setName(newCustomer.getName());
            if (newCustomer.getGstin() != null)
                c.setGstin(newCustomer.getGstin());
            if (newCustomer.getPhoneNumber() != null)
                c.setPhoneNumber(newCustomer.getPhoneNumber());
            if (newCustomer.getAddress() != null)
                c.setAddress(newCustomer.getAddress());
            if (newCustomer.getOutstandingBalance() != 0.0f)
                c.setOutstandingBalance(newCustomer.getOutstandingBalance());
            return new ResponseEntity<>(customerRepo.save(c), HttpStatus.OK);
        }else{
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("customers/{customerId}")
    public String deleteCustomer(@PathVariable Long customerId) throws ResourceNotFoundException {
        return customerRepo.findById(customerId)
                .map(customer -> {
                    customerRepo.delete(customer);
                    return "Success";
                })
                .orElseThrow(() -> new ResourceNotFoundException());
    }
}
 org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.example.crudrestapi.controller.CrudControllerTest.postCustomer(CrudControllerTest.java:52)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
   @Test
    void postCustomer() throws Exception {
        Customer customer = Customer.builder().name("name").address("address").build();
        given(customerRepo.save(customer));
        mockMvc.perform(post("/customers")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(customer))//Call to other method to transform an object to a JSON
                )
                .andExpect(status().isOk());
    }

    private String asJsonString(final Object obj) {
        try {
            return new ObjectMapper().writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }