jeudi 15 avril 2021

How can I handle UsernameNotFoundException?

I've been using some previous examples of testing methods some of my work partners used and they didn't have any problem but when i use them for this project it doesn't work at all. One of my partners saw the methods and he didn't know either what was wrong. This is my test class:

    @Mock
    UserRepository dataRepository;
    
    @Autowired
    protected UserService userService;
    
    private User u;
    

    @BeforeEach()
    void setUp() {
        u = new User();
        u.setId(23L);
        u.setUsername("test");
        u.setPassword("Pass1234.");
        u.setInfo(null);
        this.dataRepository.save(u);
    }
    
    @Test
    void testLoadUserByUsername() throws Exception {
        when(dataRepository.findByUsername(anyString())).thenReturn(u);
        userService.loadUserByUsername("test");
        assertEquals(u, userService.loadUserByUsername(anyString()));
        verify(dataRepository).findByUsername(anyString());


}
        
    @Test
    void testFindAllUsers() throws Exception {
        List<User> user = this.userService.findAllUsers();
        Assertions.assertNotNull(user);
    
}

}

When i execute the test i get the same trace every time and it is, for the first method:

org.springframework.security.core.userdetails.UsernameNotFoundException: User can't be found
    at com.project.UserService.loadUserByUsername(UserService.java:41)

I don't know what could it be because i'm searching the same name i'm setting just a few lines above so if u could help me i would appreciate it.

The UserService class is:

@Autowired
private BCryptPasswordEncoder               passw;

@Autowired
private UserRepository                  userRepository;

@Autowired
private DataRepository  dataRepository;


@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    User user = this.userRepository.findByUsername(username);

    if (user == null) {
        throw new UsernameNotFoundException("User can't be found");
    }

    return user;
}


public List<User> findAllUsers() {

    List<User> l = new ArrayList<User>();
    l = (List<User>) this.userRepository.findAll();

    return l;
}


public void save(final User u) {
    this.userRepository.save(u);
}

}

And the line of the code that is pointed by the exception is:

userService.loadUserByUsername("test");

Thank u so much.

Aucun commentaire:

Enregistrer un commentaire