DemoMongodbRestApiApplicationTests.java
2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.krunal.mongodb.it;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.krunal.mongodb.DemoMongodbRestApiApplication;
import com.krunal.mongodb.model.User;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.reactive.function.client.WebClient;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoMongodbRestApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoMongodbRestApiApplicationTests {
private static final User USER = new User("2", "hari", "bhajan", 1);
private String URI_FOR_OPERATION = null;
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate testRestTemplate;
@Autowired
private WebClient.Builder webClientBuilder;
@Bean
HttpHeaders getHeader() {
return new HttpHeaders();
}
@Bean
public WebClient.Builder getWebClientBuilder() {
return WebClient.builder();
}
private HttpHeaders header = null;
ResponseEntity<String> responseEntity = null;
@Test
public void testCreateUser() throws JsonProcessingException {
URI_FOR_OPERATION = "/user/create";
String inputJson = converToJson(USER);
HttpEntity<User> userEntity = new HttpEntity<User>(USER, header);
responseEntity = testRestTemplate.exchange(fullUrlWithPort(URI_FOR_OPERATION)
, HttpMethod.POST, userEntity, String.class);
String responseToJson = responseEntity.getBody();
Assert.assertEquals(inputJson, responseToJson);
/* String user=webClientBuilder.build().post()
.uri(fullUrlWithPort(URI_FOR_OPERATION))
.body(Mono.just(USER),User.class)
.retrieve().bodyToMono(User.class).block().toString();
Assert.assertEquals(USER.toString(), user);*/
}
@Test
public void testFindAll() throws JsonProcessingException {
URI_FOR_OPERATION = "/user/getall";
responseEntity = testRestTemplate.exchange(fullUrlWithPort(URI_FOR_OPERATION)
, HttpMethod.GET, null, String.class);
Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}
private String converToJson(Object object) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(object);
}
private String fullUrlWithPort(String uri) {
return "http://localhost:" + port + uri;
}
}