我有一个服务类说'HostService'
@Service
class HostService {
@Autowired
private val platformService: PlatformService = null
def views: Option[HostView] = {
val ip = "10.x.x.x"
if (!this.isReachable(ip))
throw new IPNotFoundException
else{
var versionInfo: Option[String] = null
versionInfo = platformService.contextPathOf("version") match {
case versionInfo if (versionInfo == Some(null)) => Option("")
case versionInfo => versionInfo
}
}
}
def isReachable(ip:String) :Boolean = {
// makes a URl connection and checks if IP is reachable
}
现在我想使用Mockito编写单元测试用例'HostServiceTest'。我将创建一个主机服务和模拟平台服务的实例,并将此主机服务实例用于模拟isReachable方法。
class HostServiceTest extends FlatSpec with Mockables with OptionValues with BeforeAndAfter {
var platformService: PlatformService = _
before {
platformService = mock[PlatformService]
when(platformService.contextPathOf((anyString()))).thenReturn(Option("1.0.0-SNAPSHOT"))
}
it should "return response with out error " in {
val hostService: HostService = new HostService
mockField(hostService, "platformService", platformService)
val hostServiceSpy = spy(hostService)
doReturn(true).when(hostServiceSpy ).isReachable(anyString())
val data = hostService.views
// Some validation Checks
}
在测试用例中,不是调用isReachable的模拟方法,而是进入实际方法。
我看到了这个问题Mockito: Trying to spy on method is calling the original method 我确实按照他们建议的方式进行了抄袭,但它却称之为实际的stub。
这可能有什么问题?
答案 0 :(得分:1)
在模拟该字段时,请确保它是' var'如果是val,则模拟器不能将该字段设置为新值。
您的HostService将platformService声明为val(表示final)
class HostService {
@Autowired
private val platformService: PlatformService = null
一旦创建了hostService,它就会有一个最终的字段platformService。
val hostService: HostService = new HostService
当您尝试模拟platformService字段时,它将模拟API将尝试重置platformService,但它不是最终的。
mockField(hostService, "platformService", platformService)
修复:尝试将platformService更改为var
private var platformService: PlatformService = null