0

I am testing this feature:

fun findByUsername(username: String): Account {
        return accountRepo.findByUsername(username).orElseThrow {
            UsernameNotFoundException("Username was not found")
        }
    }

here is my test

@Test
    fun checkFindByUsername() {
        val userRegistrationForm = UserRegistrationForm("testUser3", "123", "eee", false)
        val user = accountService.createAccount(userRegistrationForm)

        assertEquals(accountRepo.findByUsername("").orElseThrow {
            UsernameNotFoundException("Username was not found")
        }, "Username was not found")
    }

what to do to make the test pass? Do you need to use any specific assertion? sorry, understand that stupid question

wolfi
  • 21
  • 1
  • 3
  • when i ise assertThrows, appearts error: org.opentest4j.AssertionFailedError: Expected org.springframework.security.core.userdetails.UsernameNotFoundException to be thrown, but nothing was thrown. – wolfi May 15 '20 at 01:53

2 Answers2

2

Under the assumption that you're using JUnit (5), you can use Assertions.assertThrows.

Assertions.assertThrows(UsernameNotFoundException.class, () -> 
    accountRepo.findByUsername("")
);
Marv
  • 3,517
  • 2
  • 22
  • 47
  • when i ise assertThrows, appearts error: org.opentest4j.AssertionFailedError: Expected org.springframework.security.core.userdetails.UsernameNotFoundException to be thrown, but nothing was thrown. – wolfi May 15 '20 at 01:53
  • 2
    Then it seems like the Exception is no thrown... – Marv May 15 '20 at 01:55
0

Use the expected parameter of the @Test annotation:

@Test(expected = UsernameNotFoundException.class)
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    I would recommend using `assertThrows` over this if JUnit 5 is available, because it specifies the exact point where the exception is expected and acceptable. – Marv May 15 '20 at 01:40