如何为实现Spring Security 的项目创建基于JUnit5的单元测试?

kulphzqa  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(140)

如何为实现springs的项目创建单元测试 AuthenticationProver 延伸 WebSecurityConfigurerAdapter ? 现在,我已经为我的“authenticationservice”和测试运行添加了mockbeans,但我认为这不是正确的方法。

@AutoConfigureMockMvc
@AutoConfigureJsonTesters
@WebMvcTest(PortfolioController.class)
public class PortfolioControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private JacksonTester<Portfolio> json;

    @MockBean
    private UserService userService;

    @MockBean
    private PortfolioService portfolioService;

    @MockBean
    private AuthenticationService authenticationService;

    // Removing test methods for brevity
}
@Service
public class AuthenticationService implements AuthenticationProvider {
    private final UserRepository userRepository;
    private final HashService hashService;

    public AuthenticationService(UserRepository userRepository, HashService hashService) {
        this.userRepository = userRepository;
        this.hashService = hashService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // Removing implementation details for brevity
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final AuthenticationService authenticationService;

    public SecurityConfig(AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(this.authenticationService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Removing implementation details for brevity
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题