我正在尝试为控制器编写单元测试。我正在@MockBean
中嘲笑一些依赖项(例如服务类)。但是还有其他一些依赖关系,我想像往常一样由spring创建bean。这可能吗?
@RunWith(SpringRunner.class)
@WebMvcTest(JwtAuthenticationController.class)
public class JwtControllerTests {
@MockBean
private JwtUserDetailsService jwtUserDetailsService;
@MockBean
private AuthenticationManager authenticationManager;
@ ? ? ?
private JwtTokenUtil jwtTokenUtil
public void auth_Success() throws Exception {
when(
jwtUserDetailsService.loadUserByUsername(anyString())
).thenReturn(adminUserDetails);
RequestBuilder request = MockMvcRequestBuilders
.post("/api/v1/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.content(authBody);
}
}
控制器代码:
public class JwtAuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
}
答案 0 :(得分:0)
您有@WebMvcTest。
可用于重点关注的Spring MVC测试的注释 仅在Spring MVC组件上。
您需要使用@SpringBootTest(classes = Application.class)并配置MockMvc。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class JwtControllerTests {
private MockMvc mockMvc;
@MockBean
private JwtUserDetailsService jwtUserDetailsService;
@MockBean
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(new JwtAuthenticationController(authenticationManager,jwtUserDetailsService,jwtTokenUtil))
.addInterceptors(interceptor)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
public void auth_Success() throws Exception {
when(
jwtUserDetailsService.loadUserByUsername(anyString())
).thenReturn(adminUserDetails);
RequestBuilder request = MockMvcRequestBuilders
.post("/api/v1/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.content(authBody);
mockMvc.perform(request).andExpect(status().isOk());
}
更改JwtAuthenticationController以接受构造函数的依赖关系。