简体   繁体   English

在运行时告诉字段Spock是否嘲笑或监视了字段的方法

[英]Way to tell at runtime if a field has been mocked or spied by Spock

Is there a way to tell at runtime if a field of a Java instance has been mocked by Spock? 有没有一种方法可以在运行时判断Spock是否嘲笑了Java实例的字段? I'd like to use this information to conditionally exclude fields from being serialized when I'm debugging and use GSON to create a string representation to print to standard output. 我想使用此信息在调试时有条件地从序列中排除字段,并使用GSON创建字符串表示形式以打印到标准输出。

If the field you need to check is not set, namely returns null or other default value (true, false, 0) it can't be distinguished. 如果未设置您需要检查的字段,即返回null或其他默认值(true,false,0),则无法区分。

However you can check if the class which declares field is a Mock itself. 但是,您可以检查声明字段的类本身是否是Mock The easiest (but may the least reliable as well) way to check if class is mock, spy or other object is to invoke toString() method an check if starts with Mock for type 'SomeType' . 检查类是否为模拟,间谍或其他对象的最简单(但也可能是最不可靠)的方法是调用toString()方法,以检查Mock for type 'SomeType'是否Mock for type 'SomeType' All mocked objects have toString() overridden. 所有模拟的对象均具有toString()被覆盖。 Also class name - obtained via getClass().getName() - will be similar to: org.SomeType$$EnhancerByCGLIB$$815ccad0 . 另外,通过getClass().getName()获得的类名称将类似于: org.SomeType$$EnhancerByCGLIB$$815ccad0

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

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