Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Paul Yorde
10,497 PointsHow do Custom Exceptions work in Java | Junit
I am building a vending machine test using a custom exception and testing in junit4.
The error message I'm getting when running the test is this:
java.lang.AssertionError:
Expected: (an instance of NotEnoughCoinsException and exception with message a
string containing "Price 0.0")
but: exception with message a string containing "Price 0.0" message was null
Stacktrace was: NotEnoughCoinsException
at VendingMachine.selectProduct(VendingMachine.java:54)
The VendingMachine method:
public String selectProduct(String productInput) throws NotEnoughCoinsException {
switch (productInput) {
case COLA:
if(currentAmount >= ONE_DOLLAR)
return COLA;
else
throw new NotEnoughCoinsException("Price " + currentAmount);
case CHIPS:
return CHIPS;
case CANDY:
return CANDY;
}
return "";
}
The Test code:
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldDisplayPriceWhenProductIsSelectedAndInsufficientAmountIsAvailable() throws Exception {
thrown.expect(NotEnoughCoinsException.class);
thrown.expectMessage("Price " + vend.getCurrentAmount());
vend.insertCoin(QUARTER);
vend.selectProduct(COLA);
}
The custom Exception
public class NotEnoughCoinsException extends Exception {
private static final long serialVersionUID = 1L;
public NotEnoughCoinsException(String message) {
super();
}
}
1 Answer
Wout Ceulemans
17,603 PointsIn the constructor of your custom NotEnoughCoinsException you ask for the message, but you don't do anything with it. You call the default constructor of Exception, which takes no arguments. This will make the message null.
In order to make it work you have to pass the message to the correct constructor of Exception. To be more exact, you have to use this Exception constructor: https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html#Exception(java.lang.String)
Paul Yorde
10,497 PointsPaul Yorde
10,497 PointsThank you!