本文介绍了如何使用 jMockit 模拟标记为 final 并具有私有构造函数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JMockit 编写一些基于状态的测试来模拟 CSVRecord.问题是 CSVRecordfinal(这意味着我必须使用像 JMockit 这样的模拟框架)和 CSVRecord's构造函数具有包私有可见性.

I would like to write some state based tests using JMockit to mock up CSVRecord. The problem is that CSVRecord is final (which means I have to use a mocking framework like JMockit) and CSVRecord's constructor has package private visibility.

因为它是包私有的,所以我不能调用 new CSVRecord(arg, arg, ...),这意味着我永远不能实例化我的模拟.它的父类 CSVParser 是唯一可以创建实例的类.

Since it is package private, I can't call new CSVRecord(arg, arg, ...), which means I can never I instantiate my mock. Its parent, CSVParser, is the only class that can create an instance.

JMockit 有办法处理这种情况吗?

Does JMockit have a way to deal with this scenario?

注意:JMockitMockito 是我们在这个项目中使用的唯一框架.没有其他框架是可以接受的.我更喜欢使用 MockUp.

note: JMockit or Mockito are the only frameworks we use on this project. No other framework will be acceptable. My preference is to use a MockUp.

推荐答案

这听起来更像是 CSVRecord 不适合模拟.如果可能,最好针对另一个在内部使用它的公共类进行测试.

It sounds more like CSVRecord isn't a good candidate for mocking. If possible, tests targetting another public class which uses it internally would be preferable.

否则,JMockit 提供了一个带有 newInstance 方法的 Deencapsulation 类.

Otherwise, JMockit provides a Deencapsulation class with newInstance methods.

作为旁注,Mockito 仅支持基于行为的测试;JMockit 提供模型"(MockUp),但这与编写纯基于状态的黑盒测试不同.

As a side note, Mockito only supports behavior-based tests; JMockit provides "mock-ups" (MockUp), but it's not the same as writing a pure state-based black box test.

这篇关于如何使用 jMockit 模拟标记为 final 并具有私有构造函数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 01:31