[英]How to test a rest service returning boolean in response using TestRestTemplate
I have a rest service written using Spring Boot as below:我有一个使用 Spring Boot 编写的休息服务,如下所示:
@RestController
class MyBankingController{
@GetMapping("/getCards")
public SomePOJO getCards(){}
@GetMapping("/cardPresent")
public boolean isCardPresent(@RequestParam(value = "username") String
username){
//calls service layer to return primitive true or false
}
}
Below is my test class:下面是我的测试课:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyBankingApplication.class, webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyBankingControllerIT {
private MyBankingController myBankingController;
private TestRestTemplate restTemplate;
private static final String BASE_URL = "/company/cards";
HttpHeaders headers = new HttpHeaders();
String username = "1234";
@Autowired
private MyBankingService myBankingService;
@LocalServerPort
private int port;
@Before
public void setUp() throws Exception {
myBankingController = new MyBankingController(myBankingService);
restTemplate = new TestRestTemplate();
}
@Test
public void testIsCardPresent() throws JSONException {
String url = BASE_URL+"cardPresent?username="+username;
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<Boolean> response = restTemplate.exchange(
createURLWithPort(url),
HttpMethod.GET, entity, Boolean.class);
assertTrue(response.getBody());
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
}
I am unable to test this boolean return type.我无法测试这个布尔返回类型。 I have tried a couple of different things but it doesn't work.
我尝试了几种不同的方法,但它不起作用。 I am getting the below error.
我收到以下错误。
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.lang.Boolean out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.Boolean out of START_OBJECT token at [Source: (PushbackInputStream); line: 1, column: 1]
Please note that the above code is just a customized version of the actual code and that at the moment it is not possible to change the return type or the controller.请注意,以上代码只是实际代码的定制版本,目前无法更改返回类型或控制器。 Could you be able to tell me how to test this?
你能告诉我如何测试这个吗?
Change the response type to String as sketched below, and test for "true" "false" and it should work:将响应类型更改为字符串,如下所示,并测试“true”“false”,它应该可以工作:
ResponseEntity<String> response = restTemplate.exchange(
createURLWithPort(url),
HttpMethod.GET, entity, String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.