如何在MockMVC中模拟某些bean,而不模拟其他bean?

时间:2019-10-24 18:35:28

标签: spring spring-boot junit mocking mockito

我正在尝试为控制器编写单元测试。我正在@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;
}

1 个答案:

答案 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以接受构造函数的依赖关系。