【发布时间】:2016-07-12 22:27:22
【问题描述】:
由于某些无法解释的原因,我在构造函数中分配的字段 (currentExp) 在使用模拟进行单元测试时未正确设置。我正在分配字段currentExp,方法是使用我的Storage 类(使用SharedPreferences)通过loadExperience 方法加载它。当我对此进行单元测试时,我想模拟 Storage 类,所以 loadexperience 返回值 10。
这是我的具体Experience 类:
public class Experience extends StorageObject {
private int currentExp = 0;
public Experience() {
this(new Storage());
}
@VisibleForTesting
protected Experience(Storage storage) {
super(storage);
} // Debug point #2
@Override
protected void init(Storage storage) {
this.currentExp = storage.loadExperience();
} // Debug point #1
}
它扩展了StorageObject:
public abstract class StorageObject {
protected Storage storage;
protected StorageObject() {
this(new Storage());
}
@VisibleForTesting
protected StorageObject(Storage storage) {
this.storage = storage;
init(storage);
}
protected abstract void init(Storage storage);
}
这是我的单元测试:
@Test
public void testConstructor_StorageValuePositive_IsSetAsCurrentExp() {
int expectedSavedExp = 10;
Storage storageMock = mock(Storage.class);
doReturn(expectedSavedExp).when(storageMock).loadExperience();
Experience exp = new Experience(storageMock);
assertEquals(expectedSavedExp, exp.getCurrentExp());
}
在调试时,我发现模拟确实有效,并且在调试点 #1 将值 10 分配给 currentExp。然后不久之后,在调试点 #2 处,该值似乎又为 0。
任何人都知道这里发生了什么,以及如何解决这个问题?
【问题讨论】:
标签: android unit-testing constructor mocking abstract-class