模拟Runtime.getRuntime()? [英] Mock Runtime.getRuntime()?

查看:230
本文介绍了模拟Runtime.getRuntime()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提出任何关于如何最好地使用EasyMock预期调用 Runtime.getRuntime()。exec(xxx)

Can anyone make any suggestions about how best to use EasyMock to expect a call to Runtime.getRuntime().exec(xxx)?

我可以将调用移动到另一个实现接口的类中的方法,但宁愿不在理想的世界中。

I could move the call into a method in another class that implements an interface, but would rather not in an ideal world.

interface RuntimeWrapper {
    ProcessWrapper execute(String command) throws IOException;
}

interface ProcessWrapper {
    int waitFor() throws InterruptedException;
}

我想知道是否有人有任何其他建议?

I was wondering if anyone had any other suggestions?

推荐答案

您的课程不应该调用 Runtime.getRuntime()。它应该期望将 Runtime 设置为其依赖项,并使用它。然后在测试中,您可以轻松提供模拟并将其设置为依赖项。

Your class shouldn't call Runtime.getRuntime(). it should expect a Runtime to be set as its dependency, and work with it. Then in your test you can easily provide a mock and set it as a dependency.

作为旁注,我建议观看本次OO设计可测试性讲座

As a sidenote, I'd suggest watching this lecture on OO Design for testability.

更新: 我没有看到私有构造函数。您可以尝试使用 java字节码检测为了添加另一个构造函数或使构造函数公开,但这可能也是不可能的(如果该类有一些限制)。

Update: I didn't see the private constructor. You can try using java bytecode instrumentation in order to add another constructor or make the constructor public, but that might turn out to be impossible as well (if there are some restrictions on that class).

所以你的选择是制作一个包装器(正如你在问题中所建议的那样),并遵循依赖注入方法。

So your option is to make a wrapper (as you suggested in the question), and follow the dependency-injection approach.

这篇关于模拟Runtime.getRuntime()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆