0

I need to write unit tests with Java for an Android application. What I currently need to do is to create an object Picture and use it for some tests. The problem with this object is, that it's constructor has a method call:

public Picture(File imageFile) {
    this.filename = imageFile.getName();
    this.imageDimension = getImageDimension();
    /.../
}

Method getImageDimension() references some other classes, therefore I would prefer for separability to just mock it's result. For mocking, I need to give Mockito a constructor, so it seems to me like a chicken-egg problem.

So, is there a chance to mock a function used in the object constructor with Mockito? If no, how could this situation be solved without changing the original code?

4

1 回答 1

1

通常你会模拟整个对象,而不仅仅是它的一部分。但如果它不是最终的,请创建一个 Picture 的子类并覆盖构造函数并在那里执行您的自定义操作。这样您就可以避免调用原始构造函数,并且可以测试实例。

如果它是最终的,那么单元测试就会变得非常困难。如果您实际上没有对这个特定类进行单元测试,则应该完全模拟图片对象或根本不模拟。

顺便说一句,这就是为什么你不应该让你的构造函数工作:它导致代码难以测试和模拟。将对象初始化与逻辑分开是一件好事。可能您在这里想要的是一个额外的构造函数,它将文件名和维度作为构造函数参数。

于 2013-08-13T14:10:08.083 回答