forked from JavaOPs/topjava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestUtil.java
More file actions
52 lines (40 loc) · 2.13 KB
/
Copy pathTestUtil.java
File metadata and controls
52 lines (40 loc) · 2.13 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
package ru.javawebinar.topjava;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import ru.javawebinar.topjava.model.User;
import ru.javawebinar.topjava.web.json.JsonUtil;
import java.io.UnsupportedEncodingException;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static ru.javawebinar.topjava.web.json.JsonUtil.writeValue;
public class TestUtil {
public static String getContent(ResultActions action) throws UnsupportedEncodingException {
return action.andReturn().getResponse().getContentAsString();
}
public static ResultActions print(ResultActions action) throws UnsupportedEncodingException {
System.out.println(getContent(action));
return action;
}
public static <T> T readFromJson(ResultActions action, Class<T> clazz) throws UnsupportedEncodingException {
return JsonUtil.readValue(getContent(action), clazz);
}
public static <T> ResultMatcher contentJson(T expected) {
return content().json(writeValue(expected));
}
public static <T> ResultMatcher contentJsonArray(T... expected) {
return contentJson(expected);
}
public static void mockAuthorize(User user) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(new AuthorizedUser(user), null, user.getRoles()));
}
public static RequestPostProcessor userHttpBasic(User user) {
return SecurityMockMvcRequestPostProcessors.httpBasic(user.getEmail(), user.getPassword());
}
public static RequestPostProcessor userAuth(User user) {
return SecurityMockMvcRequestPostProcessors.authentication(new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()));
}
}