I am trying to test a method methodB
(as shown in the code below). I want to return directly from methodA
without going into the actual code of methodA
.
I have used when/thenReturn
and doReturn/when
but didn't get any success. The test case goes into the real code of methodA
. Also tried using spy
with Class A
instance but didn't get any success.
Actual 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 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?