I wrote unit test (JUnit 4) that performs some logic and writes result to file. In @Before annotated method it creates file and in @After the file should be deleted. It isn’t though, and I can’t figure it out, why.
I am using Google Guava 10.01 Files API. Here’s my unit test code:
public class CashierTest extends ContextedTest {
private File cashierFile;
@Before
public void createFile() throws Exception {
cashierFile = new File("D://workspace-sts/spring-miso/cashier.txt");
cashierFile.createNewFile();
}
@After
public void release() {
if (cashierFile.exists()) {
if (!cashierFile.delete()) {
System.out.println("Couldn't delete cashier file");
}
}
cashierFile = null;
}
@Test
public void testCashier() throws Exception {
// file shouldn't contain any text
assertFalse(Files.toString(cashierFile, Charset.defaultCharset()).length() > 0);
Cashier cashier = (Cashier) context.getBean("cashier");
ShoppingCart cart = (ShoppingCart) context.getBean("shoppingCartPrototype");
cashier.checkout(cart);
assertTrue(cashierFile.exists());
// file should contain text now
assertTrue(Files.toString(cashierFile, Charset.defaultCharset()).length() > 0);
}
@Override
protected void setPath() {
path = "sk/xorty/advancedioc/beans.xml";
}
}
Note: ContextedTest superclass is my test which holds Spring container it isn’t relevant atm.
Simply instanting a
Filedoes not mean that an actual file will be created. CallcreateNewFile()orcreateTempFile()on that instance for this.Within your test method you don’t seem to pass that file reference to anyone that could possibly create the file or write anything in it… Am I missing something or is the code you posted missing some key lines ?