简体   繁体   中英

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? 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.

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.

However you can check if the class which declares field is a Mock itself. 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' . All mocked objects have toString() overridden. Also class name - obtained via getClass().getName() - will be similar to: org.SomeType$$EnhancerByCGLIB$$815ccad0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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