安卓Kotlin单元测试/ Collection, ArrayList依赖的解耦/ MockK
本来这种依赖的解耦很复杂,以为不能实现。
原来,要了解for的运行机制,然后进行mock,就可以实现单元测试。
1. 这里是通过迭代遍历Collection。
需要的是.size和.iterator.hasNext()。
fun getBeaconsInfo(beacons:Collection<Beacon>):HashMap<Int,Double>{ var infos = HashMap<Int,Double>() if (beacons.size > 0) { for(beacon in beacons){ infos.put(beacon.id3.toInt(),beacon.distance) } } return infos }
使用了Kotlin测试工具Mockk
@Test fun getBeaconsInfo1(){ val beacons = mockk<Collection<Beacon>>() every { beacons.size } returns 3 every { beacons.iterator().hasNext() } returns true andThen true andThen true andThen false every { beacons.iterator().next().id3.toInt() } returns 8 andThen 5 andThen 1 every { beacons.iterator().next().distance } returns 5.0 andThen 10.0 andThen 1.0 val infos = HashMap<Int, Double>() infos[8] = 5.0 infos[5] = 10.0 infos[1] = 1.0 assertEquals(infos,SISSIController.instance.getBeaconsInfo(beacons)) }
2. 这里是单纯for循环。
此外,我这里用到了.last()
需要的是.size和isEmpty()。
fun normalize(path: ArrayList<Arrival>): HashMap<Int, Double> { var rating:HashMap<Int,Double> = HashMap() var sum = path.last().time - path[0].time for (i in 1 until path.size) { rating.put(path[i - 1].beacon, (path[i].time - path[i - 1].time).toInt() * 1.0 / sum) } return rating }
@Test fun normalize() { val path = mockk<ArrayList<Arrival>>() every { path.isEmpty() } returns false every { path.size } returns 5 every { path.last().time } returns 90000 every { path[0].beacon } returns 1 every { path[0].time } returns 50000 every { path[1].beacon } returns 2 every { path[1].time } returns 60000 every { path[2].beacon } returns 3 every { path[2].time } returns 70000 every { path[3].beacon } returns 4 every { path[3].time } returns 80000 every { path[4].beacon } returns 5 every { path[4].time } returns 90000 val rating: HashMap<Int, Double> = HashMap() rating[1] = 0.25 rating[2] = 0.25 rating[3] = 0.25 rating[4] = 0.25 assertEquals(rating, SISSIController.instance.normalize(path)) }