我有一个UsernameController,我正在尝试为其建立单元测试。 我需要模拟一个User对象,而我尝试使用@WithMockUser
Controller:
@RestController
@RequestMapping(value = "/username")
public class UsernameController {
/* Simply return the username */
@RequestMapping(method = RequestMethod.GET)
public CommonWebResponse<Map<String, Object>> read(@CurrentlyLoggedUser User currentUser) {
Map<String, Object> result = new HashMap<>();
result.put("username", currentUser.getUsername());
result.put(
"roles",
currentUser
.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList()));
return new SuccessWebResponse<>(result);
}
}
CurrentlyLogged用户界面:
@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal
public @interface CurrentlyLoggedUser {}
单元测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UsernameControllerTest {
private MockMvc mvc;
private UsernameController controller;
@Before
public void setUp(){
controller = new UsernameController();
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
@WithMockUser(username = "admin", roles = {"USER", "ADMIN"})
public void testGetUsername() throws Exception{
MockHttpServletResponse response = mvc.perform(get("/username")
.contentType(MediaType.APPLICATION_JSON)
).andReturn().getResponse();
Assert.assertNotNull(response);
}
}
但是,当我运行此测试时,出现以下异常错误:
No primary or default constructor found for class org.springframework.security.core.userdetails.User
如何正确模拟spring User对象,以便此控制器方法将其接受?