I'm working on some modifications to a DAO. The modifications included refactoring some code to keep a couple of methods from calling .getResultsList()
multiple times. Instead, the results are cached to a List
and all subsequent code works with that list making the code run more efficiently by only reaching out to the database once.
I was asked to create jUnit tests for the methods I modified to ensure that something like this won't happen again in the future. Is it possible for me to validate how many times a local variable inside a method has a function called on it using mockito?
I've seen several questions/forum posts on using verify
to validate the number of calls made on a mocked object. But I don't actually have access to mock this object as it is being created inside the method any not being passed in.
Basically -
myDao
has a class variable EntityManager
called em
, the em.createNamedQuery()
function is stored to a TypedQuery
variable q
. This q
is what .getResultsList was being called on multiple times.
In my jUnit test, is it possible to listen to what's happening inside the method I'm calling on my mocked Dao and make sure that q.getResultsList
is only called once while the method is running?
UPDATE
myDao
in my test class is configured using the @Autowired
annotation like so:
@Autowired
MyDao myDao;
It is defined in the applicationContext.xml like so:
<bean id="myDao" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.mypackage.myDao"/>
</bean>
The method I'm calling is inside that DAO, so I call myDao.myMethod(myVar);
Inside myMethod
is the q variable I'm wanting to listen to. It's a local variable.
If you are mocking myDao then you aren't going to be able to validate code within myDao.
To test this you need a test for the myDao class. In that unit test you can mock EntityManager
and have createNamedQuery
return a mocked query. Then you can use mockito's verify
and times(1)
to verify that getResultsList()
was only called once on the mocked query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.