发布实体为 testresttemplate 返回 null

问题描述

我正在使用测试其余模板进行集成测试,但对于 postForEntity 方法,我将响应主体设为 null,但我看到了在此方面运行良好的示例,但我无法解决我的问题,

PFB 我的测试用例

@RunWith(springrunner.class)
@SpringBoottest(webEnvironment = SpringBoottest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class PersonControllerTests {

    
    @Autowired
    private TestRestTemplate restTemplate;
    
    @MockBean
    private PersonRepository mockRepository;
    
    @Before
    public void init() {
        List<Person> list = new ArrayList<>();
        Person p1 = new Person("dumm1","lastName1",22);
        Person p2 = new Person("dumm2","lastName2",32);
        p1.setId(1l);
        list.add(p2);
        list.add(p1);
        when(mockRepository.findAll()).thenReturn(list);
        when(mockRepository.findById(1l)).thenReturn(Optional.of( p1 ));
    }

    
    @Test
    public void createPerson() throws Exception {
    Person  p = new Person("dummy1","dumm2",11);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    httpentity<Person> httpentity = new httpentity<Person>(p,headers);
    ResponseEntity<String> response = restTemplate
            .withBasicAuth("user","password")
            
            .postForEntity("/persons/create",httpentity,String.class);
    assertEquals(HttpStatus.OK,response.getStatusCode());
    //assertEquals(MediaType.APPLICATION_JSON,response.getHeaders().getContentType());
    assertEquals(11,response.getBody());
    }

PFB 我的原始代码

@RestController
@RequestMapping("/persons")
public class PersonController {

    @Autowired
    PersonRepository personRepository;
    
    @GetMapping("/all")
    public Iterable<Person> getAllUser() {
        return personRepository.findAll();
    }
    
    @PostMapping(value ="/create",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Person createuser( @RequestBody Person person) {
        return personRepository.save(person);
    }
}

我相信我犯了一些愚蠢的错误但无法理解

解决方法

您正在使用 @MockBean 作为您的 PersonRepository。没有任何存根设置,Mockito 为引用类型返回 null

这就是 return personRepository.save(person); 在您的测试期间返回 null 的原因。

你可以存根你的模拟来模拟它的行为:

// import static org.mockito.ArgumentMatchers.any;

when(personRepository.save(ArgumentMatchers.any(Person.class))).thenAnswer(invocation -> {
  Person person = invocation.getArgument(0);
  // I assume you have an id field
  person.setId(42L);
  return person;
});