Since all classes in Kotlin are final by default, and Mockito can't spy on final classes:
Cannot mock/spy class bye.persistence.jdbcTrial
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
And this guide (6 July, Danny Preussler) is saying that a framework is neccessary to resolve this issue.
Now was I wondering, is it possible to test a REST API (using Spring MockMvc). Below is my tester code:
package byeTest.persistenceTest
import bye.domain.User
import bye.persistence.jdbcTrial
import bye.spring.GreetingController
import byeTest.persistenceTest.RestAPITest.RootConfig
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.BDDMockito.given
import org.mockito.Mockito
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import org.springframework.test.context.web.WebAppConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration(classes = arrayOf(RootConfig::class))
@WebAppConfiguration
open class RestAPITest {
var mockMvc: MockMvc? = null;
@Autowired
var wac : WebApplicationContext? = null;
@Autowired
var jdbcTrial : jdbcTrial? = null
@Autowired
var todoServiceMock : GreetingController? = null;
@Before
open fun setup(){
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build()
given(this.jdbcTrial?.getUserById(2)).willReturn(User(2,"uname","typ"));
}
@Test
open public fun find_2(){
mockMvc!!.perform(get("/user/2").accept(MediaType.APPLICATION_JSON))
.andExpect(content().string("{\"id\":2,\"username\":\"uname\",\"usertype\":\"typ\"}"))
}
@Configuration
open class RootConfig{
@Bean
open fun jdbcTrial():jdbcTrial{
return Mockito.mock(jdbcTrial::class.java)
}
}
}
I set all the functions and classes used to open since according to the kotlin docs this is the exact opposite of final. But using this (everywhere) still throws the exception mentioned above.
Aucun commentaire:
Enregistrer un commentaire