Home > Net >  Mockito object always giving a NullPointer exception
Mockito object always giving a NullPointer exception

Time:11-07

This is the class that I want to test.

open class Foo(bar :Bar){
   fun someMethod() = bar.anotherMethod()
}

And I have a builder class to get Foo mock instance since Mockito cant mock constructor arguments.

open class FooBuilder{
   fun makeFoo(bar:Bar) = Foo(bar)
}

Here is my approach to make the mock Objects and verify.

var fooBuilderMock = mock(FooBuilder::class)
var barMock = mock(Bar::class)
var fooMock = mock(Foo::class) 
Mockito.`when`(fooBuilderMock.makeFoo(barMock)).thenReturn(fooMock)
fooMock.someMethod()
Mockito.verify(barMock, Mockito.times(1)).anotherMethod()

I am getting a null pointer exception on barMock object.

CodePudding user response:

Don't use the Builder, there is no need for it. Additionally, don't mock the class that you are trying to test. If you do it, your test makes no sense.

class FooTest {

    private val barMock = mock(Bar::class)
    private lateinit var foo: Foo

    @BeforeEach
    fun setUp() {
        MockitoAnnotations.initMocks(this)

        foo = Foo(barMock)
    }

    @Test
    fun `Your test name`() {
        // Arrange
        Mockito.`when`(barMock.anotherMethod()).thenReturn(// whatever it should return)

        // Act
        fooMock.someMethod()

        // Assert
        Mockito.verify(barMock, Mockito.times(1)).anotherMethod()
    }
}

As a side note consider taking a look at mockk and using it instead of Mockito. It is implemented in kotlin and thus supports it since day 1. With it, your test would look similar but follow more the kotlin "style":

class FooTest {

    @MockK
    private lateinit var barMock = mock(Bar::class)
    private lateinit var foo: Foo

    @BeforeEach
    fun setUp() {
        MockitoAnnotations.initMocks(this)

        foo = Foo(barMock)
    }

    @Test
    fun `Your test name`() {
        // Arrange
        every { barMock.anotherMethod() } returns //whatever it should return

        // Act
        foo.someMethod()

        // Assert
        verify(exactly = 1) { barMock.anotherMethod() }
    }
}
  • Related