Is it possible to use Mockito in Kotlin?
There are two possible workarounds:
private fun <T> anyObject(): T {
Mockito.anyObject<T>()
return uninitialized()
}
private fun <T> uninitialized(): T = null as T
@Test
fun myTest() {
`when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}
The other workaround is
private fun <T> anyObject(): T {
return Mockito.anyObject<T>()
}
@Test
fun myTest() {
`when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}
Here is some more discussion on this topic, where the workaround is first suggested.
Is it possible to use Mockito with Kotlin without open the class?
Mockito2 can now mock final classes as well.
However, this feature is opt-in, so you need to enable it manually.
To do so, you need to define a file /mockito-extensions/org.mockito.plugins.MockMaker
containing the line mock-maker-inline
See e.g.
http://hadihariri.com/2016/10/04/Mocking-Kotlin-With-Mockito/ or
https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#unmockable
for a quick introduction
on a side note, this currently doesn't work for android
Mockito with Kotlin Controller class
The whole test class seems a bit messy to me... You are using the @EnableSpringDataWebSupport @RunWith(MockitoJUnitRunner::class)
annotations. The standard way how to test your controller is by using the @WebMvcTest
annotation - see https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests.
Then your test class should look something like this:
@WebMvcTest(controllers = [SmelterController::class])
internal class SmelterControllerTest @Autowired constructor(
private val mockMvc: MockMvc,
) {
@MockBean
private lateinit var smelterService: SmelterService
@MockBean
private lateinit var smelterMapper: SmelterMapper
@Test
fun `list all smelters returns one item`() {
// mock behaviour of smelterService.listAll
// mock behaviour of smelterMapper.toDtoPage
// perform mockMvc call
// verify mocks
}
}
Related Topics
Why Can Array Constants Only Be Used in Initializers
Extracting Pairs of Words Using String.Split()
Accessing Post Variables Using Java Servlets
Overriding Object.Equals VS Overloading It
Creating New Generic Object with Wildcard
Java.Net.Connectexception :Connection Timed Out: Connect
How Does Java Order Items in a Hashmap or a Hashtable
Check If a Value Exists in Arraylist
How to Create Variables at Runtime in Java
Cannot Instantiate the Type List<Product>
Getting Value of Public Static Final Field/Property of a Class in Java via Reflection
Javafx Exception in Thread "Main" Java.Lang.Noclassdeffounderror: Javafx/Application/Application
How to Pause/Sleep/Wait in a Java Swing App