我正在尝试测试一个ViewModel
类,该类实例化一个Timer
的实例,并在该类的init块中安排一个任务。为了模拟Timer
的行为,我决定创建一个自定义阴影,该阴影过去对我有用。但是我不清楚为什么它对此不起作用。
要测试的课程
class MyViewModel(application: Application) : AndroidViewModel(application) {
private val timer: Timer
init {
timer = Timer()
timer.scheduleAtFixedRate(...)
}
}
测试类
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [23], shadows = [TimerShadow::class])
class FactorListViewModelUnitTest {
private lateinit var sut: MyViewModel
private lateinit var timer: Timer
private lateinit var timerShadow: TimerShadow
@Before
fun setup() {
...
sut = MyViewModel(application)
...
timer = someCodeUsingReflectionToGetField(sut, "timer") as Timer // this line works
timerShadow = Shadow.extract<TimerShadow>(timer) // ClassCastException here
}
}
TimerShadow
@Implements(Timer.class)
public class TimerShadow {
private TimerTask mTimerTask;
private long mDelay;
private long mPeriod;
@Implementation
@SuppressWarnings("checkstyle:methodname")
public void __constructor__() {
mDelay = 0;
}
@Implementation
public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
mTimerTask = task;
mDelay = delay;
mPeriod = period;
}
public TimerTask getTimerTask() {
return mTimerTask;
}
public long getDelay() {
return mDelay;
}
public long getPeriod() {
return mPeriod;
}
}
尝试提取阴影时遇到的异常是java.lang.ClassCastException: java.util.Timer cannot be cast to org.robolectric.internal.bytecode.ShadowedObject
。放入各种断点,我发现我从来没有进入影子的构造函数实现,并且可以看到Timer
中的sut
对象是真实的Timer
,而在其他情况下,阴影起作用,阴影的构造函数被拾取,我在阴影对象中看到__robo_data__
。
我想念什么?