Overwhelmed by industry, Searching for a modern day savior from another place, Inclined toward charity (The Answer - Bad Religion)
When you are writing unit tests, you must keep in mind to not have dependencies to external components. To avoid this we use mock frameworks which for me the easiest one to use is Mockito.
In this post we are going to see an "advanced" technique used in Mockito to return same argument instance on a mocked method using Answer interface.
Suppose we are writing unit tests for class which manages Person and Job classes and as operation it uses a DAO class for inserting the relationship class (M:N) between Person and Job called PersonJob.
For example class under test will look something like:
So in this case it seems obvious that you need to mock personJobDao.
Let's create the mock and record the interaction:
Yes as you can see you don't know what to return, because instance is created by class under test and in the test method you don't know which instance is created by createPersonJob method. To solve this problem, you need to use thenAnswer instead of thenReturn method:
Now we can write assertions in peace without worrying about returned instance.
Hope you have found this post useful.
We keep learning