Java – mockito – a method that stores the object returned by the mock object method
Suppose I have a mock object. I don't want to stub any of its methods, but I want to store a method of the returned object For example,
when(mockObject.method1()).thenReturn(returnValue)
How it works, but I'm looking,
when(mockObject.method1().method2()).thenReturn(returnValue)
Is that possible? If I do, I will get a NullPointerException At present, I have the first method to return a mock object, and then use the returned mock object and stub the second method However, these temporary mock objects are useless to me, and after linking many methods, they lead to many useless mock objects
Edit: actually, links may work, but my object is causing NPE This code (first line) causes NPE:
when(graphDb.index().getNodeAutoIndexer()).thenReturn(nodeAutoIndexer); when(graphDb.index().getRelationshipAutoIndexer()).thenReturn(relAutoIndexer);
But the purpose of this code is:
IndexManager indexManager = mock(IndexManager.class); when(graphDb.index()).thenReturn(indexManager); when(indexManager.getNodeAutoIndexer()).thenReturn(nodeAutoIndexer); when(graphDb.index().getRelationshipAutoIndexer()).thenReturn(relAutoIndexer);
Therefore, getnodeautoindexer () returns an AutoIndexer object. Because getrelationshipautoindexer () returns a relationshipautoindexer, the link does not work Both return values are ridiculed as follows:
nodeAutoIndexer = (AutoIndexer<Node>) mock(AutoIndexer.class); relAutoIndexer = mock(RelationshipAutoIndexer.class);
So what may lead to this problem?
Solution
No problem at all
Let's look at these four lines of code:
IndexManager indexManager = mock(IndexManager.class); when(graphDb.index()).thenReturn(indexManager); when(indexManager.getNodeAutoIndexer()).thenReturn(nodeAutoIndexer); when(graphDb.index().getRelationshipAutoIndexer()).thenReturn(relAutoIndexer);
The first line creates a mock indexmanager
The second tells mock graphdb to return the indexmanager (the simulation created on the first line) when calling the index method
The third, when calling the getnodeautoindexer method, returns the simulated indexmanager (created on the first line) to nodeautoindexer
The last line calls graphdb Index (), which returns the simulated indexmanager (you tell it in the second line) and asks the indexmanager (this is the simulation you created in the first line). When its getrelationshipautoindexer method returns relautoindexer, it is called
The last line works because you tell mock graphdb what to return when calling its index method If you haven't done this before, simulate graphdb The index () method will return null and you will have an NPE