如何在使用Mockito进行模拟测试时解决NullpointerException?

huangapple go评论88阅读模式
英文:

How to solve NullpointerException while testing mocked using mockito?

问题

**如何在使用 mockito 进行模拟测试时解决类型为 <List<NodeInfo>> 的 nodeInfoList.map { it.legalIdentities.last().name } 引发的 NullpointerException 问题**

**## 待测试的服务代码 ##**

```kotlin
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(timeout = 300000)
fun `测试获取下拉数据`() {
    val cordaRPCOps = Mockito.mock(CordaRPCOps::class.java)
    val listNodeInfoMock = Mockito.mock(List::class.java) as List<net.corda.core.node.NodeInfo>
    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)
}

<details>
<summary>英文:</summary>

**How to solve NullpointerException nodeInfoList.map { it.legalIdentities.last().name } where nodeInfoList is of type &lt;List&lt;NodeInfo&gt;&gt; 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[&quot;ownerList&quot;] = ownerList
            response[&quot;maintainerList&quot;] = 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&lt;net.corda.core.node.NodeInfo&gt;()::class.java)
        val singleMockNodeInfo = Mockito.mock(net.corda.core.node.NodeInfo::class.java)
        val x500Name = CordaX500Name.parse(&quot;O=Building Owner1,L=Tokyo,C=JP&quot;)
        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(&quot;O=Building Owner1,L=Tokyo,C=JP&quot;))).thenReturn(true)
        val dropDownData = staticDataService!!.getDropDownData()
        println(&quot;dropDownData &quot; + dropDownData)
    }




</details>


# 答案1
**得分**: 1

我认为这取决于您测试的目标,以及您是否期望该列表为null,以及您是否想要对其进行测试。一般来说,使用Mockito处理空列表有许多方法,您可以查看这个[其他帖子][1],并了解哪种方法最适合您的目的。

  [1]: https://stackoverflow.com/questions/40032794/use-mockito-to-match-a-null-list-of-a-specific-type

<details>
<summary>英文:</summary>

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][1], for example, and see what fits best with your purpose.


  [1]: https://stackoverflow.com/questions/40032794/use-mockito-to-match-a-null-list-of-a-specific-type

</details>



# 答案2
**得分**: 0

```kotlin
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
英文:
 fun ` list data Test`() {
    val x500Name = CordaX500Name.parse(&quot;O=Maintenance Operator1,L=Tokyo,C=JP&quot;)
    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&lt;NodeInfo&gt;? = null

huangapple
  • 本文由 发表于 2020年8月17日 20:41:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63451036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定