我正在测试一种引发两个不同异常的方法。这是我的标题:
@Test (expected = A8InvalidInputException.class)
public void testGuessCharacter() throws A8InvalidInputException, A8AlreadyGuessedException
{
...
}
正文有两个 try/catch 块(对 SO 的搜索导致一篇帖子说这是您测试抛出异常的方式),一个用于每个异常。在我看来,我应该把它分成两种测试方法,特别是因为我只能有一个预期的属性。但是,当我这样做时,应该测试 A8InvalidInputException 的方法需要 A8AlreadyGuessedException 的 try/catch,而应该测试 A8AlreadyGuessedException 的方法需要 A8InvalidInputException 的 try/catch。我不确定如何编写这个测试。这是我正在尝试测试的方法:
/**
* This method returns whether a specified character exists in the keyPhrase field
* @param guess a character being checked for in the keyPhrase field
* @return returns whether a specified character exists in the keyPhrase field
* @throws A8InvalidInputException if a non-valid character is passed as input to this method
* @throws A8AlreadyGuessedException if a valid character which has already been guessed is passed as input to this method
*/
public boolean guessCharacter(char guess) throws A8InvalidInputException, A8AlreadyGuessedException
{
if(isValidCharacter(guess))
{
guess = Character.toLowerCase(guess);
if(guessedCharacters.contains(guess) )
{
throw new A8AlreadyGuessedException("" + guess);
}
else
{
guessedCharacters.add(guess);
if(keyPhrase.contains("" + guess))
return true;
else
{
numberOfGuessesLeft--;
return false;
}
}
}
else
{
throw new A8InvalidInputException("" + guess);
}
}