当尝试测试 post() 剩余端点时,请参阅:json 不能为 null 或为空

When try to test post() rest endpoint see: json can not be null or empty

如果我尝试测试 post() 端点,我会看到:

java.lang.AssertionError:JSON 路径“$.firstName”

没有值

原因:java.lang.IllegalArgumentException:json 不能为 null 或为空

但是对于 get() 的测试一切正常。 在 postTest() 中,status 的结果是正确的。 我的错误在哪里? 以这种方式测试其余控制器是否正确?

@RunWith(MockitoJUnitRunner.Silent.class)
public class Temp {
    private final Employee successfullyRegisteredEmployee = new Employee(2L, "Iven");
    private final Employee employeeGetById = new Employee(2L, "Iven");


    @Mock
    private EmployeeServiceImpl serviceMock;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(new EmployeeControllerImpl( serviceMock))
                .build();
    }


    @Test
    public void getTest() throws Exception {
        when(serviceMock.getEmployee(2L)).thenReturn(employeeGetById);

        mockMvc.perform(get("/employee/get/2"))
                .andExpect(status().is(200))
                .andExpect(content().json(("{'firstName':'Iven'}")));

        verify(serviceMock).getEmployee(2L);
    }



    @Test
    public void postTest() throws Exception {
        String json = "{\n" +
                "  \"firstName\": \"Iven\"\n" 
                "}";
        when(serviceMock.register(employeeForRegister)).thenReturn(successfullyRegisteredEmployee);

        mockMvc.perform( MockMvcRequestBuilders
                .post("/employee/register")
                .content(json)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is(201))
                .andExpect(jsonPath("$.firstName", Matchers.is("Iven")));

    }
}

@RestController
@RequestMapping("/employee")
public class EmployeeControllerImpl implements EmployeeController {
    private final EmployeeService service;

    public EmployeeControllerImpl(EmployeeService service) {
        this.service = service;
    }

    @PostMapping(path = "/register",
            consumes = "application/json",
            produces = "application/json"
    )
    public ResponseEntity<Employee> registerEmployee(@Valid @RequestBody Employee employee) {
        Employee registeredEmployee = service.register(employee);
        return ResponseEntity.status(201).body(registeredEmployee);
    }
}

似乎问题出在 when(serviceMock.register(employeeForRegister)).thenReturn(successfullyRegisteredEmployee); 上。

您是否尝试在 return ResponseEntity.status(201).body(registeredEmployee); 上设置断点以检查 registeredEmployee 是否实际已满? 如果它是空的,那么尝试用 when(serviceMock.register(any())).thenReturn(successfullyRegisteredEmployee); 替换模拟,如果它有效,这意味着 equals() 方法没有被 Employee 覆盖,或者比较失败。