次のような update という名前の UserController でメソッドをテストしようとしています。
@RequestMapping(path = "/update", method = RequestMethod.PUT)
@PreAuthorize("#user.id != authentication.principal.id")
public ResponseEntity<User> update(@RequestBody final User user) {
return new ResponseEntity<>(userService.saveElement(user), HttpStatus.OK);
}
しかし、テストで id("#user.id != authentication.principal.id") にアクセスできないようです
@PreAuthorize("#user.id != authentication.principal.id") を削除すると、テストは緑色になります。追加してみました
@Test
@WithMockUser(roles = {"ADMIN"}, id={"1"})
...
}
または他の修飾子も、しかしそれはうまくいきませんでした
ユーザーコントローラー.java
@Controller
@RequestMapping(API_PATH)
public class UserController {
public static final String API_PATH = "/api/user";
private final UserService userService;
@Autowired
public UserController(final UserService userService) {
this.userService = userService;
}
@RequestMapping(path = "/update", method = RequestMethod.PUT)
@PreAuthorize("#user.id != authentication.principal.id")
public ResponseEntity<User> update(@RequestBody final User user) {
return new ResponseEntity<>(userService.saveElement(user), HttpStatus.OK);
}
}
UserControllerTest.java
@ExtendWith(SpringExtension.class)
@SpringBootTest
@ContextConfiguration(classes = {TestContextConfiguration.class})
@WebAppConfiguration
class UserControllerTest {
private MockMvc mvc;
@Autowired
private WebApplicationContext context;
@MockBean
private UserService userServiceMock;
@BeforeEach
void initTest() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
@Test
@WithMockUser(roles = {"ADMIN"})
void update() throws Exception {
final String apiPath = UserController.API_PATH + "/update";
final User user = new User();
final String userAsJsonString = TestUtils.getObjectAsJsonString(user);
mvc.perform(put(apiPath).contentType(MediaType.APPLICATION_JSON).content(userAsJsonString)).andExpect(status().isOk());
Mockito.verify(userServiceMock).saveElement(ArgumentMatchers.any(User.class));
}
}