gpt4 book ai didi

JAVA:JUnitTest,抛出两个异常的测试方法

转载 作者:行者123 更新时间:2023-12-01 06:32:55 27 4
gpt4 key购买 nike

我正在测试一种引发两个不同异常的方法。这是我的标题:

@Test (expected = A8InvalidInputException.class)

public void testGuessCharacter() throws A8InvalidInputException, A8AlreadyGuessedException
{
...
}

主体有两个 try/catch block (对 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);
}
}

最佳答案

只需在 throws 子句中添加两个异常即可:

@Test (expected = A8InvalidCharacterException.class) 
public void testInvalidCharacterScenario() throws A8InvalidInputException, A8AlreadyGuessedException { ... }

@Test (expected = A8InvalidInputException.class)
public void testInvalidInputScenario() throws A8InvalidInputException, A8AlreadyGuessedException { ... }

然后,如果一个测试抛出另一个异常(意外的异常),那么您的测试将自动失败。

关于JAVA:JUnitTest,抛出两个异常的测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com