测试示例如下
import lombok.SneakyThrows;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.mock.web.MockMultipartFile;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.http.Cookie;
import java.io.File;
import java.io.FileInputStream;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
@AutoConfigureMockMvc
public class UserControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.build();
}
@Test
public void editEmail() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/test/user/set-email?email=1121.ls.com")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}
@Test
@WithMockUser(username = "zx")
public void editEmail2() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/test/user/set-email?email=1121.ls.com")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}
@Test
@WithUserDetails(value = "9032", userDetailsServiceBeanName = "userDetailsService")
public void editEmail3() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/test/user/set-email?email=1121.ls.com")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}
@Test
public void editEmail4() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/test/user/set-email?email=1121.ls.com")
.header(LoginController.HEADER, "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ6eCIsImV4cCI6MTU4MzQ3NzczOX0.3QYooiFT-dqc6k-TMNGD7Drhl1q5gvepYtjjpG05sHaZ_sucSWbxMApRvVCTF-aWg9hYJ6_omEr63YWYKoRdbw")
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}
}