监视方法是调用实际方法而不是模拟方法

Spying a method is calling the actual method instead of the mocked one

我有一个服务class说'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 我确实遵循了他们建议的存根方式,但它正在调用实际的 one.o

这可能有什么问题?

当模拟该字段时,请确保它是 'var' 如果它是 val 模拟者无法将字段设置为新值。

您的 HostService 将 platformService 声明为 val(这意味着最终)

class HostService {
   @Autowired
   private val platformService: PlatformService = null

一旦你创建了hostService,它就会有一个final字段platformService。

val hostService: HostService = new HostService

当您尝试模拟 platformService 字段时,它会模拟 API 将尝试重置 platformService,但它不能,因为它是最终的。

mockField(hostService, "platformService", platformService)

修复:尝试将 platformService 更改为 var

private var platformService: PlatformService = null