如何在spock测试中模拟私有方法的返回值

问题描述 投票:0回答:2

我想测试一个公共方法,在其中调用另一个私有方法,我使用以下反射方式获取私有方法并尝试模拟它的返回值,但它不起作用,因为测试停止在私有的地方打电话是。有什么建议?

Method testMethod = handler.getClass().getDeclaredMethod("test", String.class)
testMethod.setAccessible(true)
testMethod.invoke(handler, "test string") >> true

testMethod如下所示:

private boolean test(String str) {
    return true;
}
java unit-testing groovy spock
2个回答
1
投票

使用cglib代理Spock模拟类。这样的代理不能模拟最终类或私有方法(因为私有方法是隐式最终的)。如果您的测试代码是用Groovy编写的(如脚本或grails应用程序),那么您可以使用Spock GroovyMock或修补元类:

setup:
  HandlerClass.metaClass.test = { true }

given: "a handler"
  def handler = new HandlerClass()

when: "i call test" 
  def r = handler.test()

then:
  r == true

但是,您应该更多地关注代码的可测试性。必须模拟类通常不是代码的可维护性和可测试性的好兆头......


0
投票

你不能使用Mockito模拟私有方法。但如果有明确需要,那么你可以试试看PowerMock。

当您为公共方法编写测试时,它们不会为私有方法编写测试。

如果在私有方法中调用了任何模拟,那么您可以通过执行以下操作来验证调用:

Mockito.verify(myMock, Mockito.times(1)).myMethod(myParams,...,...);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.