【发布时间】:2016-05-10 12:06:09
【问题描述】:
这有点 Android 特定,但它可以适用于非 Android 项目。
我有一个将FilterEntity 映射到ContentValues 的类。 FilterEntity 是我创建和控制的数据结构,而 ContentValues 是 Android SDK 的最后一个类,如果没有被模拟,它将抛出 RuntimeException。
public class FilterEntityToContentValuesMapper {
public ContentValues mapOrThrow(FilterEntity filter) {
final ContentValues values = new ContentValues();
values.put(FilterSchema.COLUMN_ID, filter.id().toString());
values.put(FilterSchema.COLUMN_NAME, filter.name());
// and others...
return values;
}
}
测试时ContentValues#put 将立即抛出RuntimeException,因为它没有被模拟,但问题是它不能被模拟有两个原因。首先ContentValues 是最终的,其次是在方法体中实例化。
为了解决第一个问题,我创建了一个ContentValuesWrapper,它提供与ContentValues 完全相同的功能,但将所有内容委托给一个真正的ContentValues 对象。对于第二个问题,我创建了一个ContentValuesWrapperFactory,它提供了ContentValuesWrapper 的实例。最终结果是这样的:
public class FilterEntityToContentValuesMapper {
private final ContentValuesWrapperFactory contentValuesWrapperFactory;
public FilterEntityToContentValuesMapper(ContentValuesWrapperFactory contentValuesWrapperFactory) {
this.contentValuesWrapperFactory = contentValuesWrapperFactory;
}
public ContentValues mapOrThrow(FilterEntity filter) {
final ContentValuesWrapper values = contentValuesWrapperFactory.createContentValuesWrapper();
values.put(FilterSchema.COLUMN_ID, filter.id().toString());
values.put(FilterSchema.COLUMN_NAME, filter.name());
// and others...
return values;
}
}
我想知道是否有更好的方法来解决这个问题,因为我正在使用 ContentValuesWrapper 复制功能。
【问题讨论】:
标签: java android unit-testing mocking android-sqlite