Java 使用对象实例化测试代码段的良好实践
是否有任何指导方针(或最佳实践)将以下内容进行整理 我有以下测试方法:Java 使用对象实例化测试代码段的良好实践,java,unit-testing,testing,kotlin,Java,Unit Testing,Testing,Kotlin,是否有任何指导方针(或最佳实践)将以下内容进行整理 我有以下测试方法: fun findProfileByPersonalInfo(personInfo: PersonalInfo): Profile? { localProfileRepository.findByPersonalInfo(personalInfo)?.let { return it } val searchParams = RemoteProfileSearchParameters()
fun findProfileByPersonalInfo(personInfo: PersonalInfo): Profile? {
localProfileRepository.findByPersonalInfo(personalInfo)?.let {
return it
}
val searchParams = RemoteProfileSearchParameters()
//... Some mapping from personalInfo to searchParams
remoteProfileRepository.findRemoteProfile(searchParams)?.let {
val profile = profileFactory.create(remoteProfile)
return save(profile)
}
return null
}
当我开始为此函数编写单元测试时,我意识到:
val profile=profileFactory.create(remoteProfile)
既简单又方便,因为我可以模拟此调用的结果,并分别测试从remoteProfile
到profile
的映射。这样,如果我更改映射逻辑,我就不会破坏对findProfileByPersonalInfo
的测试,这很好personalInfo
映射到searchParams
的逻辑属于findProfileByPersonalInfo
,那么维护测试就不正确,也很困难RemoteProfileSearchParameters(personInfo:PersonalInfo)
在这里可能是最明智的。根据复杂性的不同,这可能会被重构为一个工厂方法或一个实际的工厂对象,但通常这不会是您的第一步谢谢你的回复,我大体上同意你的看法。但是,在构造函数的情况下,如何测试实例化逻辑(即使可以用一些框架模拟构造函数,这也是一个“否”)?您只需实例化所述类的一个对象,并根据构造函数中提供的输入确认该对象的行为符合预期。嘲笑是没有意义的,因为你会嘲笑你想要测试的东西,从而测试你的嘲笑。如果在测试中调用构造函数是不可能的,例如由于外部依赖关系,那么您将希望在主代码中注入这些依赖关系,并在测试中模拟这些依赖关系。