-1

I'm quite a newbie on this aera, and unfortunately following various tutorial doesn't help that much...

I'm using data injection pattern (Dagger), so let's consider class A,B,C

class C @Inject constructor() {
    fun doIt(i: Int): Int{
        return i*100
    }
}

class B {
    @Inject
    constructor()

    fun doIt(i: Int): Int{
        return i*10
    }
}


class A @Inject constructor(val b: B) {  // (primary) constructor injection

    @Inject // field injection
    lateinit var c: C // late = after init/constructor

    fun doIt(i: Int): Int{
        return c.doIt(i) + b.doIt(i) + 1
    }

}

How can I test A class in a unit test (with MockK) ?

I was naively thinking about something like this:

internal class ExampleUnitTest2 {
    @MockK
    lateinit var c: C

    @MockK
    lateinit var b: B

    @Before
    fun setUp() = MockKAnnotations.init(this)

    @Test
    fun myTest() {
        coEvery { c.doIt(5) } returns 500
        coEvery { b.doIt(5) } returns 50

        val a = A(b)
        assertEquals(a.doIt(5), 555)
    }
}

But clearly I don't understand how this thing works ;)

chtimi59
  • 469
  • 6
  • 9

1 Answers1

0

actually much easier that I thought...

internal class ExampleUnitTest2 {

    @Test
    fun myTest() {
        val a = A(mockk())
        a.c = mockk()

        coEvery { a.c.doIt(5) } returns 400
        coEvery { a.b.doIt(5) } returns 40
        assertEquals(a.doIt(5), 445)
    }
}
chtimi59
  • 469
  • 6
  • 9