【问题标题】:How to write a test that expects an error to be issued in java [duplicate]如何编写一个期望在java中发出错误的测试[重复]
【发布时间】:2020-08-31 17:51:10
【问题描述】:

我正在测试这个功能:

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

这是我的测试

@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")
    }

怎样做才能使测试通过? 你需要使用任何特定的断言吗? 对不起,理解这个愚蠢的问题

【问题讨论】:

  • 当我使用 assertThrows 时,出现错误:org.opentest4j.AssertionFailedError: Expected org.springframework.security.core.userdetails.UsernameNotFoundException to be throw,但没有抛出任何东西。

标签: java kotlin testing


【解决方案1】:

假设您使用的是 JUnit (5),您可以使用 Assertions.assertThrows

Assertions.assertThrows(UsernameNotFoundException.class, () -> 
    accountRepo.findByUsername("")
);

【讨论】:

  • 当我使用 assertThrows 时,出现错误:org.opentest4j.AssertionFailedError: Expected org.springframework.security.core.userdetails.UsernameNotFoundException to be throw,但没有抛出任何东西。
  • 那么好像没有抛出异常...
【解决方案2】:

使用@Test注解的expected参数:

@Test(expected = UsernameNotFoundException.class)

【讨论】:

  • 如果 JUnit 5 可用,我建议在此使用 assertThrows,因为它指定了预期和可接受异常的确切点。
猜你喜欢
  • 2011-05-07
  • 2018-07-26
  • 2019-11-30
  • 1970-01-01
  • 2018-08-26
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多