问题
I want to create a test method for this void method:
/**
* @param speler speler die zijn wedstrijdronde heeft afgemaakt
* @param score score van de speler
* @throws GeenSpelerException als de persoon geen speler is
*/
@Override
public void scoreToPar(Speler speler, int score) throws GeenSpelerException {
if (speler.speeltWedstrijd(this.spelers,speler)) //boolean
{
throw new GeenSpelerException();
}
speler.setScore(score); // set score into player
I've made this test method for it:
@Test
void scoreToParTest() throws GeenSpelerException {
wed.isIngeschreven(speler); // add speler to first list
wed.isSpeler(); // add speler from first list to second list (to spelers list)
wed.scoreToPar(speler, 70);
assertEquals(70, speler.getScore()); // check if the score was set correctly
}
But when I run the test it says test failed and throws the exception. When I run the first method in my main it does exactly what I want but in the test it fails...
How can I write a good test for this method?
If it helps this is the boolean method that is checked in the if of the method I want to test.
@Override
public boolean speeltWedstrijd(List<Speler> spelers, Participant participant) {
return spelers.contains(participant);
}
回答1:
Apologies if I didn't understand your code intentions, but based on your code comments, it seems your test code will throw an error as,
wed.isSpeler(); // add speler from first list to second list (to spelers list)
which will add speler to spelers list
So speeltWedstrijd will return contains True and scoreToPar will throw GeenSpelerException exception.
As suggested by JekBP, you can use code to handle exception, but based on your comment, it seems you are using Junit 5, which has more powerful assertThrows like,
@Test
void scoreToParTest()
Assertions.assertThrows(GeenSpelerException.class, () -> {
wed.isIngeschreven(speler); // add speler to first list
wed.isSpeler(); // add speler from first list to second list (to spelers list)
wed.scoreToPar(speler, 70);
});
}
I hope this helps!!!
回答2:
I think you want to use mock as in mockito:
@Test
void scoreToParTest() throws GeenSpelerException {
var speler = mock(Speler.class);
wed.scoreToPar(speler, 70);
verify(speler).setScore(70);
}
You verify that scoreToPar
is effectively doing what it should: set the score to the value it should.
回答3:
Maybe you can use this annotation in your test class's test method so that it will pass the test once the expected exception GeenSpelerException is indeed thrown.
@Test(expected = GeenSpelerException.class)
void scoreToParTest() throws GeenSpelerException {
wed.isIngeschreven(speler); // add speler to first list
wed.isSpeler(); // add speler from first list to second list (to spelers list)
wed.scoreToPar(speler, 70);
assertEquals(70, speler.getScore()); // check if the score was set correctly
}
来源:https://stackoverflow.com/questions/62372588/junit-java-create-test-method-for-void-with-exception