Bom dia, caros!
Desenvolví um monitor de arquivos, para que o mesmo fique sempre observando um .properties e, se esse .properties for alterado, ele recarrega as propriedades do sistema. Até aqui, tudo bem, mas… como eu desenvolvo um teste unitário para esse código? Qualquer dica é bem vinda!
Segue abaixo o código:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PropertiesWatchdog extends TimerTask{
private final Log logger = LogFactory.getLog(PropertiesWatchdog.class);
public static final String SOURCE_FILE = "C:\\SOA\\Codigo\\Fachada\\FachadaSoaACrm\\ConsultarClienteFSACrm\\trunk\\config\\FachadaSoaACrm-AmdocsServices.properties";
private File sourceFile;
private Properties properties;
private long timeToUpdate;
private long lastModified;
private boolean started;
protected PropertiesWatchdog(File sourceFile) {
this(sourceFile, 5000);
}
protected PropertiesWatchdog(File sourceFile, long timeToUpdate) {
this.sourceFile = sourceFile;
this.timeToUpdate = timeToUpdate;
start();
}
private static PropertiesWatchdog instance = new PropertiesWatchdog(new File(SOURCE_FILE));
public static PropertiesWatchdog getInstance()
{
return instance;
}
protected boolean isStarted() {
return started;
}
protected void setStarted(boolean started) {
this.started = started;
}
protected long getLastModified() {
return lastModified;
}
protected void setLastModified (long lastModified) {
this.lastModified = lastModified;
}
public void start() {
if (isStarted()) {
throw new RuntimeException("This watchdog cannot be restarted.");
}
Timer timer = new Timer(true);
timer.schedule(this, 0, timeToUpdate);
setStarted(true);
}
public synchronized Properties getProperties() {
while (this.properties == null) {
try {
wait();
} catch (InterruptedException e) {
return null;
}
}
notifyAll();
return new Properties(this.properties);
}
@Override
public void run() {
long lastModified = sourceFile.lastModified();
if (lastModified > getLastModified()) {
synchronized (this) {
Properties props;
FileInputStream fis = null;
try {
props = new Properties();
props.load(fis = new FileInputStream(sourceFile));
this.properties = props;
setLastModified(lastModified);
}
catch (IOException ex) {
logger.warn("IOException thrown when trying to read the file " + SOURCE_FILE, ex);
}
finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
logger.warn("IOException thrown when trying to close the stream to the file " + SOURCE_FILE, e);
}
}
}
notifyAll();
}
}
}
}
Grato!