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
Kyle Hebert
13,391 PointsCould someone point me to an explanation of why we could expect the FavoriteNotFoundException in the service tests?
Why were we able to use @Test(expected = ...) when testing the FavoriteService, but not when testing the FavoriteController? Does it have something to do with which parts of the Spring app container are running when?
3 Answers
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsThat is because Exception is handled in Controller, and when it is handled, error page is generated.
When you catch exception in your code, you cannot test whether this exception was thrown, because it is handled.
Compare these two examples:
// this method could be tested with @Test(expected = ...)
public void methodThrowingException() throws Exception {
if (somethingIsTrue) {
throw new Exception();
}
}
// this method could NOT be tested with @Test(expected = ...) because exception is handled
// note that although exception is thrown by method inside, because it is handled, we don't put
// any signature like "throws Exception"
public void method() {
try {
methodThrowingException();
} catch (Exception ex) {
System.out.println("Exception happened");
}
}
Now take a look at Controller method: you see
- no Exception signature
- All exception in controllers in Spring are handled, even if you don't write your specific @ExceptionHandler method for them. For more on exceptions see: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Kyle Hebert
13,391 PointsThat makes total sense. Thanks for clearing that up!