Junit/Java create test method for void with exception

Ronny Giezen :

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);
}
ihimanshu19 :

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!!!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related