测试在不应该通过的时候通过

发布于 2025-01-10 06:53:49 字数 1412 浏览 1 评论 0原文

身份验证方法:

 @PostMapping("/login")
    public ResponseEntity<String> signIn(@RequestBody LoginDto loginDto) {
        try {
            Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                    loginDto.getEmail(), loginDto.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return new ResponseEntity<>("User signed-in successfully!", HttpStatus.OK);
        } catch (BadCredentialsException e) {
            return new ResponseEntity<>("Invalid credentials", HttpStatus.UNAUTHORIZED);
        }
    }

测试:

@Test
    void shouldLogin() throws Exception {
        LoginDto loginDto = new LoginDto("admin", "ye2esyes");
        String expectedMessage = "User signed-in successfully!";
        mvc.perform(MockMvcRequestBuilders
                        .post("/auth/login")
                        .content(objectMapper.writeValueAsString(loginDto))
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(expectedMessage));
    }

这些凭据是错误的,但测试仍然通过。 当我尝试使用邮递员登录时,我实际上得到了 401 和“无效凭据”,但是当我使用 Mockmvc 进行测试时,它总是通过。 我正在使用Spring安全

Authentication method:

 @PostMapping("/login")
    public ResponseEntity<String> signIn(@RequestBody LoginDto loginDto) {
        try {
            Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                    loginDto.getEmail(), loginDto.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return new ResponseEntity<>("User signed-in successfully!", HttpStatus.OK);
        } catch (BadCredentialsException e) {
            return new ResponseEntity<>("Invalid credentials", HttpStatus.UNAUTHORIZED);
        }
    }

Test:

@Test
    void shouldLogin() throws Exception {
        LoginDto loginDto = new LoginDto("admin", "ye2esyes");
        String expectedMessage = "User signed-in successfully!";
        mvc.perform(MockMvcRequestBuilders
                        .post("/auth/login")
                        .content(objectMapper.writeValueAsString(loginDto))
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(expectedMessage));
    }

Those are wrong credentials but the test is still passing.
When i try to login using postman i actually get 401 with "Invalid credentials" But when i test with Mockmvc it's always passing.
I'm using Spring Security

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伤痕我心 2025-01-17 06:53:49

您需要模拟authenticationManager.authenticate以抛出BadCredentialsException以使其失败。

You need to mock authenticationManager.authenticate to throw BadCredentialsException to make it fails.

夜血缘 2025-01-17 06:53:49

您必须模拟身份验证管理器,这可以按以下代码片段完成:

Mockito.doThrow(BadCredentialsException.class)
    .when(authenticationManager.authenticate(new 
    UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())));

这应该可以正常工作!

You have to mock the Authentication Manager and that can be done as below code snippet:

Mockito.doThrow(BadCredentialsException.class)
    .when(authenticationManager.authenticate(new 
    UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())));

This should work fine !!

梦在深巷 2025-01-17 06:53:49

事实证明我很愚蠢,我忘记了我正在嘲笑 bean,所以实际上并没有与数据库的连接。
我最终将身份验证代码移动到返回布尔值的authenticate()方法内的UserService类,然后我对该方法进行了存根测试并测试了控制器,一切正常。
我现在的测试:

@Test
    void shouldReturnUnauthorized() throws  Exception{
        final LoginDto validLoginDto = new LoginDto("admin", "yesyesyes");
        final String expectedMessage = "Invalid credentials";

        Mockito.when(userService.authenticate(validLoginDto)).thenReturn(false);

        mvc.perform(MockMvcRequestBuilders
                        .post("/auth/login")
                        .content(objectMapper.writeValueAsString(validLoginDto))
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isUnauthorized())
                .andExpect(content().string(expectedMessage));
    }

It just turned out that I'm dumb and I forgot that I'm mocking the beans so there isn't actually a connection to the database.
I just ended up moving the authentication code to UserService class inside an authenticate() method that returns a boolean, then I stubbed the method and tested the controller and everything is working fine.
My test now:

@Test
    void shouldReturnUnauthorized() throws  Exception{
        final LoginDto validLoginDto = new LoginDto("admin", "yesyesyes");
        final String expectedMessage = "Invalid credentials";

        Mockito.when(userService.authenticate(validLoginDto)).thenReturn(false);

        mvc.perform(MockMvcRequestBuilders
                        .post("/auth/login")
                        .content(objectMapper.writeValueAsString(validLoginDto))
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isUnauthorized())
                .andExpect(content().string(expectedMessage));
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文