I'm working on a mixed JVM project: Classes are mainly in Java and tests in Kotlin.
So I have a Java MyClass
which extends a ParentClass
. Both are Jakarta @Entity
. They are separated since ParentClass
can be used in other places:
@Entity
@Setter
@Getter
public class MyClass extends ParentClass {
// some attributes
}
And ParentClass
has attributes only with getter and no setters (is mandatory to not modify these values since the object is created):
@MappedSuperclass
@Getter
public class ParentClass {
private String value = "";
}
Now I'm testing some parts of the code and trying to mock this object to update value to a non null value.
Since there are no setters
, the idea is to create mock to be able to modify the getValue()
and return other value avoiding reflection.
I've tried to use something like mock.when(myMock.getValue()).thenReturn("my string")
but it doesn't works.
In kotlin tests I've tried multiple lines:
val myMock = mock<MyClass>(CALLS_REAL_METHODS)
`when`(myMock.value).thenReturn("")
// or using mockito kotlin
whenever(myMock.value).thenReturn("")
First line is trying to force to call the real getter and then mock the getter in some of the next two lines and get desired value in that way.
But it seems that not work's in that way.
Also I've tried this answer
val myMock = mock<MyClass>()
// And also
val myMock = org.mockito.kotlin.mock<MyClass>()
// And these two
`when`(myMock.value).thenReturn("")
whenever(myMock.value).thenReturn("")
None of them works, I still have the "empty" object created for mockito with all values null/objects default.
Also tried:
val mock1: MyClass = mock(MyClass::class.java)
`when`(mock1.value).thenReturn("")
whenever(mock1.value).thenReturn("")
val mock2: MyClass = mock();
`when`(mock2.value).thenReturn("")
whenever(mock2.value).thenReturn("")
val mock3: MyClass = mock(CALLS_REAL_METHODS)
`when`(mock3.value).thenReturn("")
whenever(mock3.value).thenReturn("")
None of them works, my mock class has default values. But not other is that problem but also I want to modify the parent class which is not mocked.
So, what I'm missing? Is any inter-op problem using Java and Kotlin? Is some @Entity
or @MappedSuperclass
weird thing?
Do I will need to use reflection?
Thanks in advance,
You need to create a spy, not a mock.
val mySpy = spy(MyClass())
println(mySpy.value) // original value
`when`(mySpy.value).thenReturn("stubbedValue")
println(mySpy.value) // stubbed value