首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring安全性、测试MVC和模拟服务

Spring安全性、测试MVC和模拟服务
EN

Stack Overflow用户
提问于 2017-01-16 20:04:55
回答 2查看 706关注 0票数 0

我想测试我的控制器,它有@PreAuthorize,也有我想模拟的服务

PlayerController.java

代码语言:javascript
复制
@RestController
@RequestMapping(value = "/player")
public class PlayerController {
  @Autowired
  private PlayerService playerService;

  @PreAuthorize("hasAuthority('ADMIN')")
  @RequestMapping(value = "/all", method = RequestMethod.GET, produces = "application/json")
  public
  @ResponseBody
  ResponseEntity<List<String>> loadByAdmin()
  throws Exception {
    return new ResponseEntity<>(playerService.getPlayers(), HttpStatus.OK);
  }
}

PlayerServiceImpl.java

代码语言:javascript
复制
@Service
public class PlayerServiceImpl implements PlayerService{
  @Autowired
  private PlayerRepo playerRepo;

  @Transactional(readOnly = true)
  public List<String> getPlayers()() {
    return playerRepo.findAll();
  }
}

第一次尝试:在这种情况下-测试可以工作,但正如您所看到的,authoritySOMEONE,所以它应该失败,因为只访问授权ADMIN

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebAppConfig.class, SecurityConfiguration.class})
public class PlayerControllerTest {
  private MockMvc mockMvc;

  @Autowired
  private FilterChainProxy springSecurityFilterChain;

  @Mock
  private PlayerService playerService;

  @InjectMocks
  private PlayerController playerController;

  @Test
  public void loadByAdmin()
  throws Exception {
    Player player = new player();
    when(playerService.getPlayers()).thenReturn(Collections.singletonList(player));

    mockMvc.perform(get("/circuit/all").with(user("adm").password("123")
        .authorities(new SimpleGrantedAuthority("SOMEONE"))) //not failed
        .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());

    verify(playerService, times(1)).getPlayers();
    verifyNoMoreInteractions(playerService);
  }


  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    mockMvc = MockMvcBuilders
        .standaloneSetup(playerController)
        .apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
        .build();
}

第二次尝试:所以我尝试了另一种方法,它适用于不同的权限,但在这种情况下,我不能模拟PlayerService

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebAppConfig.class, SecurityConfiguration.class})
public class PlayerControllerTest {
  private MockMvc mockMvc;

  @Autowired
  private WebApplicationContext wac;

  @Mock
  private PlayerService playerService;

  @InjectMocks
  private PlayerController playerController;

  @Test
  public void loadByAdmin()
  throws Exception {
    Player player = new player();
    when(playerService.getPlayers()).thenReturn(Collections.singletonList(player)); //not mocked

    mockMvc.perform(get("/circuit/all").with(user("adm").password("123")
        .authorities(new SimpleGrantedAuthority("ADMIN")))
        .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());

    verify(playerService, times(1)).getPlayers(); //no interaction
    verifyNoMoreInteractions(playerService);  //no interaction
  }


  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    this.mockMvc.webAppContextSetup(wac)
            .apply(springSecurity())
            .build();
}

那么,我能为模拟PlayerService和测试授权做些什么呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-25 16:57:37

已经通过反射解决了这个问题

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebAppConfig.class})
public class PlayerControllerTest {
  private MockMvc mockMvc;

  @Mock
  private PlayerService playerService;

  @Autowired
  private PlayerController playerController;

  @Autowired
  private FilterChainProxy springSecurityFilterChain;

  @Test
  public void loadByAdmin()
  throws Exception {
    Player player = new player();
    when(playerService.getPlayers()).thenReturn(Collections.singletonList(player)); //success

    mockMvc.perform(get("/circuit/all").with(user("adm").password("123")
        .authorities(new SimpleGrantedAuthority("ADMIN")))
        .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());

    verify(playerService, times(1)).getPlayers(); //was called
    verifyNoMoreInteractions(playerService);  
  }


  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    this.mockMvc = MockMvcBuilders.standaloneSetup(playerController)
        .apply(springSecurity(springSecurityFilterChain)).build();

    ReflectionTestUtils.setField(playerController, "playerService", playerService);
}
票数 0
EN

Stack Overflow用户

发布于 2017-01-16 20:30:28

你能给我们看一下PlayerService的实现吗?

你也可以尝试在setUp方法上添加一个球员,在@ @Autowire on playerService中删除该球员后,用管理员权限检查球员。因为这是一个集成测试,所以@Autowire应该可以工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41676057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档