我正在使用Spring Boot研究Kotlin,并且试图将Serenity用作报告。 但是我对Mockito遇到了一些问题,因为我无法模拟代码的最后一部分。
那是我的情况:
@RestController
@RequestMapping("/person")
class PersonController {
@Autowired
private lateinit var personUseCase : PersonUseCase
@GetMapping("/all")
fun findAllPeople(): DataModelResponse<List<PersonDataModelResponse>> {
return DataModelResponse(
PersonDataModelResponseMapper.transform(personUseCase.findAll()))
}
}
@Component
class PersonUseCase {
fun findAll(): List<PersonEntity> {
val personImpl : Person = PersonImplementation()
return personImpl.findAll()
}
}
class PersonImplementation : Person {
private val personDaoResponse : PersonDaoResponse = PersonDaoResponse()
override fun findAll(): List<PersonEntity> {
val listPeopleDao = personDaoResponse.findAll()
return PersonDaoMapper.transform(listPeopleDao)
}
}
internal class PersonDaoResponse (
val identification: Long = 0,
val personName: String = "") {
fun findAll(): List<PersonDaoResponse> {
return listOf(PersonDaoResponse(1, "José"))
}
}
我正在尝试在集成测试中模拟我的Dao:
@RunWith(SerenityRunner::class)
@WithTag("Integration")
@AutoConfigureMockMvc
@WebMvcTest
class PersonControllerTest {
@InjectMocks
private lateinit var personController : PersonController
@InjectMocks
private lateinit var personImplementation : PersonImplementation
@SpyBean
private lateinit var personUseCase : PersonUseCase
@Spy
private val personDaoResponse = PersonDaoResponse()
@Autowired
private lateinit var webApplicationContext: WebApplicationContext
@Autowired
private lateinit var mockMvc: MockMvc
@Rule @JvmField
var springMethodIntegration = SpringIntegrationMethodRule()
@Before
fun init() {
MockitoAnnotations.initMocks(this)
reset(personDaoResponse)
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build()
this.mockMvc = MockMvcBuilders.standaloneSetup(personController).setMessageConverters(MappingJackson2HttpMessageConverter()).build()
}
@Test
fun `integration success`() {
doReturn(listOf(PersonDaoResponse(999L, "Zé")))
.`when`(this.personDaoResponse).findAll()
val result = this.personController.findAllPeople()
assertNotNull(result)
assertEquals(999L, result.data[0].personId)
assertEquals("Zé", result.data[0].name)
}
}
如果执行某些操作,我知道此模拟程序有效,我尝试调用模拟方法: assertEquals(999L,this.personDaoResponse.findAll()[0] .identification)
如何在这种集成测试中模拟此Dao?
答案 0 :(得分:1)
不幸的是,我对Mockito问题没有答案,因为我离开Mockito已有很长时间了。
如果不是必须使用Mockito,我建议从Spring Boot + Kotlin经验中使用MockK(https://github.com/mockk/mockk)。如果还需要可注射的模拟Bean,则还可以添加SpringMockK(https://github.com/Ninja-Squad/springmockk)。
由于您的“ PersonDaoResponse”是在PersonImplementation类中构造的,因此可以在MockK中使用类似的方法:
every { anyConstructed<PersonDaoResponse>().findAll() } returns listOf(PersonDaoResponse(999L, "Zé"))