如何在Kotlin对象Singleton类中测试添加方法

时间:2019-09-03 12:35:23

标签: kotlin junit

我正在尝试在对象kotlin类中进行一些测试,但是当我尝试传递对象时,我的thenReturn方法会出错。我得到一个需求:单位!找到结帐​​。有人可以指出我如何进行测试?

如果删除thenReturn方法,则会出现此错误:

Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

我推荐了这个link,但我不明白。

object CheckoutRepository: CheckoutContract.Model {

    var checkout: MutableList<Checkout> = mutableListOf<Checkout>()

    override fun addProductToShoppingCart(checkoutProduct: Checkout){
        checkout.add(checkoutProduct)
    }

    override fun getProductsInShoppinCart() : List<Checkout>?{
        return checkout
    }

    override fun cleanCheckout(){
        checkout.clear()
    }
}



@Test
    fun test_with_mock() {
        val mock = mock<CheckoutContract.Model>()

        var checkout = Checkout("VOUCHER", "voucher", 35.0, 5)
        mock.addProductToShoppingCart(checkout)

        val answer = mock.getProductsInShoppinCart()
        `when`(mock.addProductToShoppingCart(checkout)).thenReturn(checkout)

        assertNotNull(checkout)
        assertEquals(checkout, answer)
    }

1 个答案:

答案 0 :(得分:0)

在您的函数中addProductToShoppingCart没有任何返回类型。

如果要检查Checkout类对功能进行更改,则测试用例将通过

override fun addProductToShoppingCart(checkoutProduct: Checkout):Checkout{
    checkout.add(checkoutProduct)
return checkout
}