我正在尝试@WebMvcTest使用类中定义的自定义安全设置 进行测试SecurityConfig:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin*").access("hasRole('ADMIN')").antMatchers("/**").permitAll().and().formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("ADMIN");
}
}
Run Code Online (Sandbox Code Playgroud)
测试类是:
@RunWith(SpringRunner.class)
@WebMvcTest(value = ExampleController.class)
public class ExampleControllerMockMVCTest {
@Autowired
private MockMvc mockMvc;
@Test
public void indexTest() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("index"));
}
@Test
public void adminTestWithoutAuthentication() throws Exception {
mockMvc.perform(get("/admin"))
.andExpect(status().is3xxRedirection()); //login form redirect
}
@Test
@WithMockUser(username="example", password="password", roles={"ANONYMOUS"})
public void adminTestWithBadAuthentication() throws …Run Code Online (Sandbox Code Playgroud) 我正在尝试为控制器编写测试用例。我不想嘲笑我的服务,因为我想将这些测试用作完整的功能测试。
我正在尝试测试此控制器:
@Controller
public class PlanController {
@Autowired
private PlanService planService;
@RequestMapping(
value = "/api/plans/{planId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@Nonnull
@JsonView(Plan.SimpleView.class)
public Plan getPlan(@RequestParam int orgId, @PathVariable int planId) {
Plan plan = planService.getPlan(orgId, planId);
return plan;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我写的测试用例:
package com.videology.skunkworks.audiencediscovery.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class) …Run Code Online (Sandbox Code Playgroud)