使用mockito的java集成测试即使在进入else语句时也不能得到覆盖

wwtsj6pe  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(425)

我试图在springboot中对restapi和mockito进行一些集成测试。即使else语句中的代码得到了测试,它仍然不能覆盖我。我添加了一些system.out.println()来确保代码在else语句中执行。当我查看调试控制台时,system.out.println()在控制台中输出,else语句被执行,但是代码仍然没有被覆盖检测到。只有if语句被检测到。我删除了if else语句以直接进入else语句中的代码,但仍然没有被检测到。我假设这可能是因为我正在使用foreach或set。
单元测试类:

@WebMvcTest(AuthController.class)
public class AuthControllerTests {

    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private ObjectMapper objectMapper;
    @MockBean
    private UserRepository userRepository;
    @MockBean
    private RoleRepository roleRepository;
    @MockBean
    private UserDetailsServiceImpl userDetailsService;
    @MockBean
    private JwtUtils jwtUtils;
    @MockBean
    PasswordEncoder encoder;
    @MockBean
    AuthenticationManager authenticationManager;

    @Test
    public void testRegisterUser() throws Exception{
        List <Role> listRoles = new ArrayList<>();
        listRoles.add(new Role(ERole.ROLE_USER));
        listRoles.add(new Role(ERole.ROLE_MODERATOR));
        listRoles.add(new Role(ERole.ROLE_ADMIN));
        Mockito.when(roleRepository.findByName(ERole.ROLE_USER)).thenReturn(java.util.Optional.ofNullable(listRoles.get(0)));
        Mockito.when(roleRepository.findByName(ERole.ROLE_MODERATOR)).thenReturn(java.util.Optional.ofNullable(listRoles.get(1)));
        Mockito.when(roleRepository.findByName(ERole.ROLE_ADMIN)).thenReturn(java.util.Optional.ofNullable(listRoles.get(2)));
        Set<String> currentRoles = new HashSet<>();
        currentRoles.add("admin");
        currentRoles.add("mod");
        currentRoles.add("user");

        SignupRequest signupRequest = new SignupRequest();
        signupRequest.setUsername("test");
        signupRequest.setEmail("test");
        signupRequest.setPassword("12341234");
        signupRequest.setRole(currentRoles);

        User user = new User(signupRequest.getUsername(),
                signupRequest.getEmail(),
                encoder.encode(signupRequest.getPassword()));

        Set<String> strRoles = signupRequest.getRole();
        System.out.println(strRoles);
        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
            System.out.println("enters if");
        }
        else {
            strRoles.forEach(role -> {
                switch (role) {
                    case "admin":
                        Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);
                        System.out.println("enters case admin");
                        break;
                    case "mod":
                        Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(modRole);
                        System.out.println("enters case mod");
                        break;
                    default:
                        Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(userRole);
                        System.out.println("enters case user");
                }
            });
        }

        user.setRoles(roles);
        String url = "/auth/signup";

        MvcResult mvcResult = mockMvc.perform(post(url).contentType("application/json")
                .content(objectMapper.writeValueAsString(user))).andExpect(status().isOk()).andReturn();
        int status = mvcResult.getResponse().getStatus();
        System.out.println(status);
    }

}

authcontroller类:

@PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
        AlreadyExistsError AlreadyExistsError = new AlreadyExistsError();

        if (userRepository.existsByUsername(signUpRequest.getUsername())) {
            AlreadyExistsError.setUserAlreadyExists(true);
        }
        if (userRepository.existsByEmail(signUpRequest.getEmail())) {
            AlreadyExistsError.setEmailAlreadyExists(true);
        }

        if (AlreadyExistsError.hasAnyErrors()){
            return ResponseEntity
                    .badRequest()
                    .body(AlreadyExistsError);
        }

        // Create new user's account
        User user = new User(signUpRequest.getUsername(), 
                             signUpRequest.getEmail(),
                             encoder.encode(signUpRequest.getPassword()));

        Set<String> strRoles = signUpRequest.getRole();
        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
        }
        else {
            strRoles.forEach(role -> {
                switch (role) {
                case "admin":
                    Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(adminRole);

                    break;
                case "mod":
                    Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(modRole);

                    break;
                default:
                    Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(userRole);
                }
            });
        }

        user.setRoles(roles);
        userRepository.save(user);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    }

    @CrossOrigin
    @GetMapping("/users")
    @ResponseBody
    public List<User> searchUser(@RequestParam String username){
        return  userRepository.findByUsernameContaining(username);
    }

我的报道是什么样子的:

vmjh9lq9

vmjh9lq91#

我的错误是我路过 .content(objectMapper.writeValueAsString(user))) 而不是 .content(objectMapper.writeValueAsString(signuprequest))) 因为 @RequestBodySignupRequest 不是 User .

0qx6xfy6

0qx6xfy62#

println调用只告诉您正在测试的else块中执行三个switch情况,而不是在实际控制器中。
在测试中使用大多数控制器代码是毫无意义的。这似乎什么也做不了。覆盖率告诉您,您在测试结束时调用控制器的方式只会触发 strRoles 存在 null .

相关问题