简体   繁体   English

如何在同一 class 中的另一个方法中模拟方法调用

[英]how to mock a method call inside another method in same class

I am trying to test a method methodB (as shown in the code below).我正在尝试测试方法methodB (如下面的代码所示)。 I want to return directly from methodA without going into the actual code of methodA .我想直接从methodA返回而不进入methodA的实际代码。 I have used when/thenReturn and doReturn/when but didn't get any success.我使用when/thenReturndoReturn/when但没有取得任何成功。 The test case goes into the real code of methodA .测试用例进入methodA的真实代码。 Also tried using spy with Class A instance but didn't get any success.还尝试将spy与 Class A实例一起使用,但没有成功。

Actual Class实际 Class

class A{
  
  fun methodA(String a): String{

    // do something
    throw new Exception("An error occured");
  }

  fun methodB(String b): String{

    try{
      methodA("test")
    } catch (e: Exception){
      println(e.message());
    }
  }

}

Test Class测试 Class

class ATest{

    private lateinit var a: A

    @Before
    fun setUp() {
        a= A() // I am initializing services in real scenario
    }

    @Test
    fun `when methodB is not valid then throw Exception`(){

        val aMock = mock(A)
        Mockito.when(aMock.methodA("test") )
            .thenThrow(UserException.INVALID_REQUEST())


        // When
        val exception: Exception = Assert.assertThrows(
            UserException::class.java
        ) {
            a.methodB("test b")
        }

        val expectedMessage = "INVALID"
        val actualMessage = exception.message

        // Then
        Assert.assertTrue(actualMessage!!.contains(expectedMessage))
    }

   
}

Can anyone please help?有人可以帮忙吗?

val a = A()
val aSpy = Mockito.spy(a)
Mockito.when(aSpy.methodA(ArgumentMatchers.any())).thenThrow(UserException.INVALID_REQUEST())

you need to get a real instance of class A and then wrap it inside a programmable wrapper which is a spy.您需要获取 class A 的真实实例,然后将其包装在作为间谍的可编程包装器中。 The param matcher of the when statement is the 2nd point of failure since "Test" is not the same instance then the "test b" string. when语句的参数匹配器是第二个失败点,因为“Test”与“test b”字符串不是同一个实例。 So you dont need to verify some parameter so skip it.所以你不需要验证一些参数所以跳过它。

If you want to verify the used parameter you can use a captor instead of ANY().如果要验证使用的参数,可以使用捕获器而不是 ANY()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM