如何使用枚举参数对方法进行单元测试?
我正在使用 junit 和 EasyMock 对我正在从事的项目进行单元测试。但是,我遇到了问题。我有很多带有枚举参数的方法。
我在尝试模拟枚举时遇到了 java.lang.NullPointerException ,并且似乎枚举无法被模拟。我在这里找到了更多信息:
http://download.oracle.com /javase/tutorial/java/javaOO/classvars.html
有什么好的方法可以在不模拟枚举的情况下对该方法进行单元测试吗?
谢谢!
编辑:Péter Török 是对的!我完全考虑了我可以为枚举插入一些东西的事实。例如:
public void methodName(String description, LocationbuildingLocation) {
其中 Location 是我的枚举,我可以将该方法调用为:
methodName("here is my description", Location.DENVER);
I'm using junit and EasyMock to do unit testing on a project I'm working on. However, I've run into a problem. I have a good handful of methods that have a parameter that is an enumeration.
I ran into the java.lang.NullPointerException when attempting to mock the enum, and it seems enums just cannot be mocked. More information I found on it here:
http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html
Is there any good way to unit test this method without mocking the enum??
Thanks!
EDIT: Péter Török was right! I was completely looking over the fact that I could just plug in something for the enum. For example:
public void methodName(String description, Location buildingLocation) {
where Location is my enum, I can call the method as:
methodName("here is my description", Location.DENVER);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
enum
包含哪些需要模拟的内容?为什么不能简单地使用可用值本身?由于枚举是(应该是)无状态且不可变的,因此它们应该可以随时用于单元测试,实例化它们应该没有问题,它们不应该保存(可变的)全局状态并且应该具有没有外部依赖关系,这使得它们很难在单元测试中使用。
对我来说,以上任何一个失败都表明存在设计问题,而不是单元测试问题。
What does your
enum
contain that you need to mock it? Why can't you just simply use the available values themselves?Since
enum
s are (supposed to be) stateless and immutable, they should be readily available for unit testing, you should have no problems in instantiating them, they should hold no (mutable) global state and should have no external dependencies which make them hard to use in unit tests.Failing any of the above would be a sign of a design problem to me rather than a unit testing problem.