Skip to content

Instantly share code, notes, and snippets.

@JoseHdez2
Last active January 28, 2020 14:17
Show Gist options
  • Save JoseHdez2/2f84d3954d5918a0d671fcaec7b01059 to your computer and use it in GitHub Desktop.
Save JoseHdez2/2f84d3954d5918a0d671fcaec7b01059 to your computer and use it in GitHub Desktop.
/**
* Use to wrap a block of code in a test that should throw an exception.
* @param errorMsg Message to show if the block of code DOESN'T throw an exception. Optional.
* @param withExceptionHaving Substring that the thrown exception must contain. Optional.
* Checking exception strings is generally discouraged, and will cause the need to
* periodically readjust the expected strings, but it guarantees the error is the expected one.
*/
fun shouldFail(errorMsg: String = "Should have failed.", withExceptionHaving: String? = null, method: () -> Unit) {
try {
method()
Assert.fail(errorMsg)
} catch (e: Exception) {
println("Test block failed with exception message: '${e.message}'.")
withExceptionHaving?.let {
Assert.assertTrue("Thrown exception message does not contain '$it'.", e.message!!.contains(it))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment