![](/img/trans.png)
[英]How to mock a method of a class being called inside another method that is being tested of the same class?
[英]how to mock a method call inside another method in same class
我正在嘗試測試方法methodB
(如下面的代碼所示)。 我想直接從methodA
返回而不進入methodA
的實際代碼。 我使用when/thenReturn
和doReturn/when
但沒有取得任何成功。 測試用例進入methodA
的真實代碼。 還嘗試將spy
與 Class A
實例一起使用,但沒有成功。
實際 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());
}
}
}
測試 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))
}
}
有人可以幫忙嗎?
val a = A()
val aSpy = Mockito.spy(a)
Mockito.when(aSpy.methodA(ArgumentMatchers.any())).thenThrow(UserException.INVALID_REQUEST())
您需要獲取 class A 的真實實例,然后將其包裝在作為間諜的可編程包裝器中。 when
語句的參數匹配器是第二個失敗點,因為“Test”與“test b”字符串不是同一個實例。 所以你不需要驗證一些參數所以跳過它。
如果要驗證使用的參數,可以使用捕獲器而不是 ANY()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.