[No Audio]
In this video, we're going to continue from the
previous video where we learn how we can use
assert.fail to explicitly fail a test and explore
where we actually might want to use that mechanism.
So let's jump in. Now you might be thinking where is
that going to be useful?
Why would I want to fail a test?
Well, you might want to do that for example,
if you're testing some exception handling.
So you can imagine having a try
[No Audio]
catch,
[No Audio]
some kind of ValidationError e.
[No Audio]
And if we supply bad input, to the system and
the test that we're invoking the test method of.
[No Audio]
Imagine this comment here is replaced with an
actual method call to the class that you're
testing and you specifically give it bad input. If you
give it bad input and you expect a ValidationError
to occur, then you expect that you immediately
then going to end up in the catch block.
Which means that if you end up on this line here,
[No Audio]
then you didn't end up in the catch block.
Which means that the class you're
testing didn't throw a ValidationError.
At that point, you might want to fail the test
and say, something like the validation didn't kick in
or some more descriptive nice error message than that,
and obviously ignore the fact that this is red here.
I've just typed in a random error
that our fictional API might throw.
Actually in fact as well, thinking about it
wouldn't be an error because narrows really like
a stop the world cup type thing.
Instead it would be an exception.
So maybe there's a checked exception which is
thrown out from this API that you've written.
So we're just supposing that here. And at
this point you're probably thinking, but you've just
told me a few seconds ago, that we can put expected
equals and then an exception class that we're expecting
to be thrown and that will make the test pass.
And that's true. You can do that.
And then you're probably thinking, well, in which
case, why would I want to even have
the try catch in the first place?
Why would even want to have this catch block?
And the reason is, because in the catch block you
might want to do some kind of extra assertions.
So for example, if you set things on this validation
exception, if you set different parameters or you
expect the ValidationException to carry some kind of
state with it, then maybe you want to do some
assertions which check, what's been set on it
and what the state is that it's carrying.
So that's one example where you could use that and get
to know how to write better tests with JUnit.
As you get more experience with it, you'll
find other opportunities to use this as well.
But that's just one example which
we wanted to give you. So let's move on.