是否可以模拟 System.identityHashCode?

再会。

我有一个工具,它通过toString向每个对象添加某些字节码生成的实现来检测项目中的对象。生成的逻辑toString无关紧要,但重要的是它的返回值取决于System.identityHashCode内部进行的调用。

现在我想用自动化测试来覆盖生成的逻辑。我创建了一个用于测试的类,为其生成toString并希望对其toString输出进行断言。很明显,这样的测试是不可重现的,因为System.identityHashCode在测试运行之间会给出不同的结果。

是否有可能以某种方式模拟System.identityHashCode或稳定给出的结果?


幕布斯6054654
浏览 128回答 2
2回答

噜噜哒

可以使用 Powermock 执行此操作,如下所述:如何使用 Mockito 模拟 System.getProperty但是,更好的方法是创建一个包装类,System然后将包装器注入到您要测试的类中。然后在您的单元测试中,您可以注入包装器的测试实现并控制系统的输出。

慕姐8265434

我将介绍一个测试接缝:@Override public String toString() {&nbsp; return toString(System.identityHashCode(object));}/** Visible for testing. */String toString(int hashCode) {&nbsp; // Your implementation here.}这样,您可以toString(int)从相邻的测试中调用任意多次,而无需担心 PowerMock 甚至 Mockito。作为替代方案,如果 System.identityHashCode 在您的类中的其他地方使用,因此结果需要保持一致,您可以在构造函数中使用替换ToIntFunction,并让默认实现传递System.identityHashCode作为对静态方法的引用。public YourWrapperClass(Object object) {&nbsp; this(object, System::identityHashCode);}/** Visible for testing. */YourWrapperClass(Object object, ToIntFunction<Object> hashCodeFunction) {&nbsp; this.object = object;&nbsp; this.hashCodeFunction = hashCodeFunction;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java