0

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?

Faraz Javed
  • 154
  • 6

1 Answers1

0
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. 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. 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().

LenglBoy
  • 297
  • 2
  • 8