【发布时间】:2021-05-17 13:25:44
【问题描述】:
我正在使用测试休息模板进行集成测试,但对于 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);
}
}
我相信我犯了一些愚蠢的错误,但无法理解
【问题讨论】:
-
您的问题中没有关于 Spring Integration 的内容:spring.io/projects/spring-integration。请,当你为你的问题选择标签时要小心。看起来你不像在你的存储库上模拟
save()
标签: resttemplate spring-boot-test