简体   繁体   English

在Spock测试中不能Mockito间谍课吗?

[英]Cannot Mockito spy class in Spock test?

I'm trying to spy a Java class in a Spock test. 我正试图在Spock测试中窥探Java类。 I've not had a problem with Mockito in Spock/Groovy before. 我以前在Spock / Groovy中没有遇到Mockito的问题。

When I try to do the following: 当我尝试执行以下操作时:

def service = spy(Service.class)

I get the following error: 我收到以下错误:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.lang.Class
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

When I do mock(Service.class) though, it works fine. 当我做mock(Service.class) ,它工作正常。

I have confirmed that the class is not final, anonymous, or primitive. 我已经确认该课程不是最终的,匿名的或原始的。

Any ideas? 有任何想法吗? I have a random generator in the class (ak) so I need to spy not mock. 我在课堂上有一个随机生成器(ak)所以我需要间谍不要嘲笑。

Thank you 谢谢

Mockito doesn't spy on Classes (or Mocks), it spies on (regular) Objects. Mockito不会监视Classes(或Mocks),它会监视(常规)对象。 Thus, instead of 因此,而不是

def service = spy(Service.class)

you have to write 你必须写

def service = spy(new Service())

(or whichever constructor is appropriate for your scenario). (或适用于您的场景的任何构造函数)。

Just an extra to Ray's answer, you can also spy on already created instances. 对Ray的答案来说,你也可以窥探已经创建的实例。 The only thing is that all methods you called before spy() was called, cannot be verified. 唯一的问题是,在调用spy()之前调用的所有方法都无法验证。 Like: 喜欢:

ClassToSpy spiedInstance;

@Before
public void before () {
    spiedInstance = new ClassToSpy();
}

@Test
public void testWillFail() {
    spiedInstance.method();
    spiedInstance = spy(spiedInstance);

    verify(spiedInstance).method();
}

@Test
public void testWillPass() {
    spiedInstance = spy(spiedInstance);
    spiedInstance.method();

    verify(spiedInstance).method();
}

The error you would get from testWillFail would be similar to: 您从testWillFail获得的错误类似于:

Wanted but not invoked:
classToSpy.method();
-> at your.package.testWillFail(TestClass.java:line)
Actually, there were zero interactions with this mock.

Due to the fact that, after spied, you did not call this method. 由于事实上,在发现后,你没有调用这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM