我想为一个方法编写一个测试,以特定的时间间隔调用观察者,以便他们执行一个方法。计时器对象在其自己的线程中运行。
待测定时器方法private long waitTime;
public Metronome(int bpm) {
    this.bpm = bpm;
    this.waitTime = calculateWaitTime();
    this.running = false;
}
public void run() {
    long startTime = 0, estimatedTime = 0, threadSleepTime = 0;
    running = true;
    while (running) {
        startTime = System.nanoTime();
        tick();// notify observers here
        estimatedTime = System.nanoTime() - startTime;
        threadSleepTime = waitTime -estimatedTime;
        threadSleepTime = threadSleepTime < 0 ? 0 : threadSleepTime;
        try {
            Thread.sleep(threadSleepTime / 1000000l);
        } catch (InterruptedException e) {
                // sth went wrong
        }
    }
}
我的测试课的片段
private int ticks;
private long startTime;
private long stopTime;
@Test
public void tickTest(){
    metronome.setBpm(600);
    startTime = System.nanoTime();
    metronome.run();
    long duration = stopTime - startTime;
    long lowThreshold  =  800000000;
    long highThreshold =  900000000;
    System.out.println(duration);
    assertTrue(lowThreshold < duration); 
    assertTrue(duration <= highThreshold);      
}
@Override
public void update(Observable o, Object arg) {
    ticks ++;       
    if(ticks == 10){
        metronome.stop();
        stopTime = System.nanoTime();
    }
}
现在,我的测试类注册为相关对象的观察者,这样我就可以计算执行 tick() 的次数。测试测量执行前后的时间,但我感觉很尴尬,以这种方式测试行为。
有什么改进测试的建议吗?