我正在尝试测试具有@PreAuthorize
需要用存根替换的服务的控制器
PlayerController.java
@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
@Service
public class PlayerServiceImpl implements PlayerService{
@Autowired
private PlayerRepo playerRepo;
@Transactional(readOnly = true)
public List<String> getPlayers()() {
return playerRepo.findAll();
}
}
第一种测试方式:在这种情况下,测试通过了,但是正如你所看到的,用户authority
已经设置SOMEONE
了,所以测试应该失败,因为 此控制器仅供管理员使用
@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"))) //Не завалился
.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 没有被替换为存根。
@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)); //Не получилось заглушить
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(); //Вызова не было
verifyNoMoreInteractions(playerService);
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc.webAppContextSetup(wac)
.apply(springSecurity())
.build();
}
如何制作它以便您可以用存根替换它PlayerService
并同时工作@PreAuthorize
?
事实证明,您可以通过反射将存根滑入真正的控制器中