我有一个类,它接受一个参数,然后从该参数填充一个私有(private) HashMap 。
Public class Table {
private Map<String, String> map = new HashMap<String, String>();
private Workbook workbook;
// approach 1
Public Table(Workbook workbook) {
this.workbook = workbook;
// populate map using workbook
}
// approach 2
Public Table(InputStream is) {
this.workbook = WorkbookFactory.create(is)
// Populate map
}
// approach 3
Public Table(File file) {
this.workbook = WorkbookFactory.create(file)
// populate map
}
}
工作簿是 Apache Poi 工作簿。 考虑到junit和mockito的最佳方法是什么?
我倾向于方法 1,因为根据此,http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/我应该避免在构造函数中使用 new 关键字。但我不希望客户端了解 Apache POI 才能使用此类。
方法 2 和方法 3 非常相似。这样我就可以传入文件或输入流,而不必担心底层实现。但是模拟会很困难,因为我无法用这种方法模拟工作簿?
最佳答案
您可以保护工厂方法和构造函数。会是这样的:
public class Table {
private final Map<String, String> map = new HashMap<String, String>();
private final Workbook workbook;
// not private for testing.
Table(Workbook workbook) {
this.workbook = workbook;
}
public static Table create(File file) {
return new Table(WorkbookFactory.create(file));
}
}
这样,您就可以使用模拟的 Workbook
来测试您的 Table
类,并且仍然不会向用户公开您正在使用它;)
@Runwith(MockitoJunitRunner.class)
public class TableTest {
@Mock
private Workbook workbook;
@InjectMocks
private Table table;
// do some sweet testing ;D
}
关于java - 将第三方对象传递给构造函数的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15839827/