Reputation: 115
How to solve NullpointerException nodeInfoList.map { it.legalIdentities.last().name } where nodeInfoList is of type <List> while testing mocked using mockito?
## Service code to be tested ##
val nodeInfoList=dataService.proxy.networkMapSnapshot()
val nodeNameList =nodeInfoList.map { it.legalIdentities.last().name }
ownerMap.map {
if(nodeNameList.contains(CordaX500Name.parse(it.value))) {
ownerList.add(it.key)
}
}
maintanenceMap.map {
if(nodeNameList.contains(CordaX500Name.parse(it.value))) {
maintainerList.add(it.key)
}
}
response["ownerList"] = ownerList
response["maintainerList"] = maintainerList
return ResponseEntity.status(200).body(response)
}
#Test function I wrote #
@Test(timeout = 300000)
fun ` get drop down data Test`() {
val cordaRPCOps = Mockito.mock(CordaRPCOps::class.java)
val listNodeInfoMock = Mockito.mock(listOf<net.corda.core.node.NodeInfo>()::class.java)
val singleMockNodeInfo = Mockito.mock(net.corda.core.node.NodeInfo::class.java)
val x500Name = CordaX500Name.parse("O=Building Owner1,L=Tokyo,C=JP")
val list500Mock2 = listOf(x500Name)
Mockito.`when`(cordaDataService!!.proxy).thenReturn(cordaRPCOps)
Mockito.`when`(cordaRPCOps.networkMapSnapshot()).thenReturn(listNodeInfoMock)
Mockito.`when`(listNodeInfoMock.map { it.legalIdentities.last().name }).thenReturn(list500Mock2)
Mockito.`when`(list500Mock2.contains(CordaX500Name.parse("O=Building Owner1,L=Tokyo,C=JP"))).thenReturn(true)
val dropDownData = staticDataService!!.getDropDownData()
println("dropDownData " + dropDownData)
}
Upvotes: 0
Views: 249
Reputation: 115
fun ` list data Test`() {
val x500Name = CordaX500Name.parse("O=Maintenance Operator1,L=Tokyo,C=JP")
val partyMock = Mockito.mock(Party::class.java)
Mockito.`when`(cordaDataService!!.proxy).thenReturn(proxyMock)
Mockito.`when`(proxyMock!!.networkMapSnapshot()).thenReturn(listNodeInfoMock)
Mockito.`when`(listNodeInfoMock!!.iterator()).thenReturn(nodeInfoIterator)
Mockito.`when`(nodeInfoIterator!!.hasNext()).thenReturn(true,false)
Mockito.`when`(nodeInfoIterator.next()).thenReturn(nodeInfoMock).thenReturn(nodeInfoMock2)
Mockito.`when`(nodeInfoMock!!.legalIdentities ).thenReturn(listOf(partyMock))
Mockito.`when`(nodeInfoMock.legalIdentities.last().name ).thenReturn(x500Name)
Mockito.`when`(list500Mock2!!.contains(x500Name)).thenReturn(true)
}
Rewritten test function like this. Nullpointer exception solved.Used @Mock for some of the mockobjects used here.
@InjectMocks
private val staticDataService: StaticDataService? = null
@Mock
private val cordaDataService: CordaDataService? = null
@Mock
private val proxyMock: CordaRPCOps? = null
@Mock
private val listNodeInfoMock: List<NodeInfo>? = null
Upvotes: 0
Reputation: 1138
I think it depends on the goal of your tests, whether you expect that list to be null or not and if you want to test it. In general, there are many ways to handle null lists with Mockito, you can see this other post, for example, and see what fits best with your purpose.
Upvotes: 1