У меня есть очень простой класс наблюдателя файла, который проверяет каждые 2 секунды, изменился ли файл и если так, onChange
метод (пусто) называют. Есть ли простой способ проверить если onChange
метод становится названным в модульном тесте?
код:
public class PropertyFileWatcher extends TimerTask {
private long timeStamp;
private File file;
public PropertyFileWatcher(File file) {
this.file = file;
this.timeStamp = file.lastModified();
}
public final void run() {
long timeStamp = file.lastModified();
if (this.timeStamp != timeStamp) {
this.timeStamp = timeStamp;
onChange(file);
}
}
protected void onChange(File file) {
System.out.println("Property file has changed");
}
}
Тест:
@Test
public void testPropertyFileWatcher() throws Exception {
File file = new File("testfile");
file.createNewFile();
PropertyFileWatcher propertyFileWatcher = new PropertyFileWatcher(file);
Timer timer = new Timer();
timer.schedule(propertyFileWatcher, 2000);
FileWriter fw = new FileWriter(file);
fw.write("blah");
fw.close();
Thread.sleep(8000);
// check if propertyFileWatcher.onChange was called
file.delete();
}
С помощью Mockito вы можете проверить, вызывается ли метод хотя бы один раз или никогда.
См. Пункт 4 на на этой странице
, например:
verify(mockedObject, times(1)).onChange(); // times(1) is the default and can be omitted
Насколько я понимаю, ваш PropertyFileWatcher
предназначен для подкласса. Так почему бы не создать подкласс так:
class TestPropertyFileWatcher extends PropertyFileWatcher
{
boolean called = false;
protected void onChange(File file) {
called = true;
}
}
...
TestPropertyFileWatcher watcher = new TestPropertyFileWatcher
...
assertTrue(watcher.called);
Вот простая модификация для вашего теста.
@Test
public void testPropertyFileWatcher() throws Exception {
final File file = new File("testfile");
file.createNewFile();
final AtomicBoolean hasCalled = new AtomicBoolean( );
PropertyFileWatcher propertyFileWatcher =
new PropertyFileWatcher(file)
{
protected void onChange ( final File localFile )
{
hasCalled.set( true );
assertEquals( file, localFile );
}
}
Timer timer = new Timer();
timer.schedule(propertyFileWatcher, 2000);
FileWriter fw = new FileWriter(file);
fw.write("blah");
fw.close();
Thread.sleep(8000);
// check if propertyFileWatcher.onChange was called
assertTrue( hasCalled.get() );
file.delete();
}