Is it possible to have multiple accepted answers in a JUnit test? So for example:
Main rock = new Main();
Assert.assertEquals("y", boxes("23"));
So for this test I want to be able to accept the result string "y" or "n" as an acceptable answer, is that possible?
使用Hamcrest CoreMatcher(包含在JUnit 4.4和更高版本中)和assertThat():
Assert.assertThat(boxes("23"), anyOf(is("y"), is("n"));
You can do it, but not with assertEquals()
. Try something like:
Assert.assertTrue(boxes("23").equals("y") || boxes("23").equals("n"));
If you have multiple possible answers, a Set
might be easier.
Set<String> possibleAnswers = new HashSet<>();
possibleAnswers.add("y");
possibleAnswers.add("n");
...
Assert.assertTrue(possibleAnswers.contains(boxes("23")));
Assertj is good at this.
import static org.assertj.core.api.Assertions.assertThat;
assertThat(boxes("23")).isIn("y", "n);
Big plus for assertj compared to hamcrest is easy use of code completion.
Apart from the fact that it is possible (eg see @dev) it is considered to be a bad practice.
Methods returning different results on the same input must (!) contain a source of non-determinism. To resolve this - mock it correctly and there will be only one result.
An explanation for accepting multiple answers could be that the assert method is called from multiple tests just asserting a generic property of the result. Generic properties could be tested more comfortable with Junit Theories .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.