When trying to use Mockito with Spring, by creating the Mock object via a bean declaration...
-
The simple answer is:
when you write Mockito.when(object.fooMethod()).then()
then fooMethod()
is actually called.
Another point is that we can't observe it first time, because it called on mocked object. But when we write when
for the second time then we have some behavior for fooMethod()
(we set it previously, in your case it Exception).
To check this better you can spy
object:
Bar spyBar = Mockito.spy(Bar.class)
when(spyBar.fooMethod()).then()...
and fooMethod()
will be actually called.
讨论(0)
-
One of the problems with Mockito.when
is that the argument you pass to it is the expression that you're trying to stub. So when you use Mockito.when
twice for the same method call, the second time you use it, you'll actually get the behaviour that you stubbed the first time.
I actually recommend NOT using Mockito.when
. There are many traps that you can fall into when you use it - quite a few cases when you need some other syntax instead. The "safer" alternative syntax is the "do" family of Mockito methods.
doReturn(value).when(mock).method(arguments ...);
doThrow(exception).when(mock).method(arguments ...);
doAnswer(answer).when(mock).method(arguments ...);
So in your case, you want
doThrow(new BadSqlGrammarException(??, ??, ??)).when(accountMapper).createBadGrammarException();
If you are starting out with Mockito, then I recommend that you learn to use the "do" family. They're the only way to mock void methods, and the Mockito documentation specifically mentions that. But they can be used whenever Mockito.when
can be used. So if you use the "do" family, you'll end up with more consistency in your tests, and less of a learning curve.
For more information about the cases when you must use the "do" family, see my answer on Forming Mockito "grammars"
讨论(0)
- 热议问题