Forum Member
Forum Member

Reputation: 163

Duplicating Kotlin mockito test code to Java

Trying to duplicate kotlin Test code to Java. Consider the following class and test class of existing kotlin code.

open class ClassX(
        val a: ObjectA,
        val b: ObjectB,
        val c: ObjectC
) {
  fun someMethod() {
.....
  }
}

Here is one of the tests

class ClassXTest : ClassX(
        a = mock(),
        b = mock(),
        c = mock()
)

Trying to mimic the same code in java

public class ClassX {
private ObjectA a;
private ObjectB b;
private ObjectC c;

public ClassX(ObjectA a, ObjectB b, ObjectC c) {
 this.a = a;
 this.b = b;
 this.c = c;
}

public void someMethod() {
...
}

}

For the test class

public class ClassXTest extends ClassX{
 public ClassX(ObjectA a, ObjectB b, ObjectC c) {
    super(a,b,c);
 }
}

My question is how do I mimick in java the mock() that is set for the base class fields as below in kotlin.

class ClassXTest : ClassX(
        a = mock(),
        b = mock(),
        c = mock()
)

Upvotes: 1

Views: 64

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

Your Kotlin code defines a subclass ClassXTest which has a constructor taking no argument and calling the super constructor with 3 mocks.

So if you want the same in Java, you also need a constructor taking no argument and calling the super constructor with 3 mocks:

public class ClassXTest extends ClassX {
    public ClassXTest() {
        super(mock(ObjectA.class), mock(ObjectB.class), mock(ObjectC.class));
    }
}

I really wonder why you create a subclass, instead of just using the existing class and passing 3 mocks as arguments to its existing constructor, though.

Upvotes: 3

Related Questions