简体   繁体   English

Java测试:通过运行代码大规模生成模拟对象

[英]Java tests: Massively generate mock objects by running your code

Hello all :) In the JVM debug mode you can inspect the objects that are present when you run your code. 大家好:)在JVM调试模式下,您可以检查运行代码时存在的对象。

This means one can create a utility that can generate a dump of those objects as ready to use mocks (or close enough, hopefully). 这意味着可以创建一种实用程序,该实用程序可以在准备好使用模拟时生成这些对象的转储(或者希望足够接近)。 Those mocks would span the entire scope of the program run, and this would help greatly in building an extensive test coverage. 这些模拟将覆盖程序运行的整个范围,这将极大地帮助建立广泛的测试覆盖范围。

Because lazy is good, I was wondering if such a utility is currently available. 因为懒惰是好的,所以我想知道这样的实用程序当前是否可用。

Best regards 最好的祝福

I don't know of a way to do this from a memory/heap dump or from debug mode but... 我不知道从内存/堆转储或调试模式执行此操作的方法,但是...

If you want to serialize arbitrary java objects to and from files for use in tests then you can use XStream to do so. 如果要在测试中使用的文件之间来回序列化任意Java对象,则可以使用XStream进行。 You could then use them in your unit tests with ease. 然后,您可以轻松地在单元测试中使用它们。

You can also use standard Java serialization if your objects are all serializable. 如果您的对象都是可序列化的,则还可以使用标准Java序列化。

To collect the data in the first place you can create an aspect using AspectJ or Spring-AOP or similar. 首先要收集数据,可以使用AspectJ或Spring-AOP或类似的东西创建一个方面。 I've done something similar in the past and it worked really well. 我过去做过类似的事情,而且效果很好。

One word of caution though: If you are doing this then any refactoring of your objects require refactoring of the test data. 不过请注意:如果执行此操作,则对象的任何重构都需要重构测试数据。 This is easier with XStream as it's XML files you are dealing with. 使用XStream可以更轻松,因为它是您要处理的XML文件。

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

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