mockito 如何在MockMVC中模拟一些bean而不模拟其他bean?

mklgxw1f  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(192)

我正在尝试为一个控制器写一个单元测试。一些依赖项(比如一个服务类)我用@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;
}
x8diyxa7

x8diyxa71#

您有@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更改为接受构造函数的依赖项。

sshcrbum

sshcrbum2#

您可以@SpyBean

@SpyBean
private JwtTokenUtil jwtTokenUtil

相关问题