-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDemoControllerTest.java
70 lines (60 loc) · 2.69 KB
/
DemoControllerTest.java
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
package io.lichtblau.springvalidationdemo1;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class DemoControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@SneakyThrows
// PASSES: No validation errors
void test1Works() {
mockMvc.perform(post("/{pathVariable}/test1", "testVariable")
.contentType(MediaType.APPLICATION_JSON) //
.content("{ \"test\": \"bodyContent\" }")) //
.andExpect(status().isOk());
}
@Test
@SneakyThrows
// FAILS: Exception is of type org.springframework.web.bind.MethodArgumentNotValidException
void test1ShouldThrowValidationException() {
val result = mockMvc.perform(post("/{pathVariable}/test1", "testVariable")
.contentType(MediaType.APPLICATION_JSON) //
.content("{ \"test\": \"\" }")) //
.andReturn();
val exception = Objects.requireNonNull(result.getResolvedException());
assertEquals(HandlerMethodValidationException.class, exception.getClass());
}
@Test
@SneakyThrows
// PASSES: No validation errors
void test2Works() {
mockMvc.perform(post("/{pathVariable}/test2", "testVariable")
.contentType(MediaType.APPLICATION_JSON) //
.content("{ \"test\": \"bodyContent\" }")) //
.andExpect(status().isOk());
}
@Test
@SneakyThrows
// PASSES: Exception is of type org.springframework.web.method.annotation.HandlerMethodValidationException
void test2ShouldThrowValidationException() {
val result = mockMvc.perform(post("/{pathVariable}/test2", "testVariable")
.contentType(MediaType.APPLICATION_JSON) //
.content("{ \"test\": \"\" }")) //
.andReturn();
val exception = Objects.requireNonNull(result.getResolvedException());
assertEquals(HandlerMethodValidationException.class, exception.getClass());
}
}