1

I want to mock the private constructor of a class with its multiple parameters (with Kotlin):

public final class Foo {

   public static class Bla {
        public final CustomType1 property1;
        public final CustomType2 property2;

        private Bla(CustomType1 param1, CustomType2 param2) {
            this.property1 = (CustomType1)Objects.requireNonNull(param1);
            this.property2 = (CustomType2)Objects.requireNonNull(param2);
        }
    }
}

Through that I try to mock the properties (property1, property2) which are otherwise nearly impossible to mock.

Karsten Gabriel
  • 3,115
  • 6
  • 19
Martin
  • 11
  • 3

3 Answers3

0

Maybe a private constructor is not what you are looking for. With a private constructor you restrict the object creation to only within the class Bla. Take a look here.

If for some reason you are required to have the constructor private, then you could try using reflections as mentioned in this issue, but keep in mind that it will essentially set the private modifier to public at runtime.

micartey
  • 128
  • 6
0

I think there are only 2 ways. The first one is already mentioned @micartey and the second one is to use PowerMockito. It's a strong tool that allow you to mock static and private methods. If we are talking about code. so it should look like this:

@RunWith(PowerMockRunner::class)
class FooTest {

    @Test
    fun testBlaConstructor() {

        val customType1Mock = mock(CustomType1::class.java)
        val customType2Mock = mock(CustomType2::class.java)

        val blaMock = mock(Bla::class.java)
        whenNew(Bla::class.java)
            .withArguments(customType1Mock, customType2Mock)
            .thenReturn(blaMock)

        val blaInstance = Bla(customType1Mock, customType2Mock)
        verify(blaMock).property1 = customType1Mock
        verify(blaMock).property2 = customType2Mock
    }

Dont forget to prepare dependency for PowerMockito

NOTE: Power Mock should be used in legacy applications where you cannot change the code which has been given to you. Often such code does not have unit/integration tests and even small change can result in bugs in application.

Feel free
  • 758
  • 5
  • 15
0

It was possible to mock the parameter property1 while wrapping it with an extending function:

internal fun Foo.Bla.getProperty1(): CustomType1 {
   return property1
}

I've accessed the value of property1 then in the implementation though getProperty1(). With that workaround it could be mocked.

Martin
  • 11
  • 3