0

I have below 2 Junits.

public class TransactionManagerTest {

String fileName = "data/test/tnx-log/tnc.log";

@Test
public void beginTransactionTest_withEmptyTxnLogFile() throws IOException, ParseException {
    new File(fileName).delete();
    TransactionManager transactionManager = new TransactionManagerImpl(fileName);

    transactionManager.beginTransaction();
    ZonedDateTime transactionStartDate = transactionManager.getTransactionStartDate();
    ZonedDateTime transactionEndDate = transactionManager.getTransactionEndDate();
    ZonedDateTime now = ZonedDateTime.now();
    Assert.assertEquals(now.getDayOfMonth(), transactionStartDate.getDayOfMonth());
    Assert.assertEquals(now.getMonth(), transactionStartDate.getMonth());
    Assert.assertEquals(now.getYear(), transactionStartDate.getYear());
    Assert.assertEquals(0, transactionStartDate.getHour());
    Assert.assertEquals(0, transactionStartDate.getMinute());
    Assert.assertEquals(0, transactionStartDate.getSecond());

    Assert.assertEquals(now.getDayOfMonth(), transactionEndDate.getDayOfMonth());
    Assert.assertEquals(now.getMonth(), transactionEndDate.getMonth());
    Assert.assertEquals(now.getYear(), transactionEndDate.getYear());
    Assert.assertEquals(now.getHour(), transactionEndDate.getHour());
}

@Test
public void beginTransactionTest_success() throws IOException, ParseException {

    File file = new File(fileName);
    System.out.println(file.exists());
    System.out.println(file.delete());
    TransactionManager transactionManager = new TransactionManagerImpl(fileName);

    File localFile = new File(fileName);
    boolean txnLogFileExist = localFile.exists();
    localFile = null;
    Assert.assertTrue(txnLogFileExist);
    ZonedDateTime startDate = ZonedDateTime.of(2019, 04, 25, 10, 35, 30, 000, ZoneId.of("UTC"));
    ZonedDateTime endDate = ZonedDateTime.of(2019, 04, 25, 10, 40, 30, 000, ZoneId.of("UTC"));

    transactionManager.beginTransaction(startDate, endDate);
    transactionManager.markSuccess();

    ZonedDateTime transactionStartDate = transactionManager.getTransactionStartDate();
    ZonedDateTime transacitonEndDate = transactionManager.getTransactionEndDate();

    Assert.assertTrue(endDate.isEqual(transactionStartDate));
    Assert.assertNotNull(transacitonEndDate);
}

And below is the implementation of My TransacitonManager and CsvService.

public class TransactionManagerImpl implements TransactionManager {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

private CsvService csvService;

public TransactionManagerImpl(String txnLogFile) throws IOException {
    this.csvService = new CsvServiceImpl(txnLogFile);
}

public class CsvServiceImpl implements CsvService {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

private String txnLogFile;

public CsvServiceImpl(String txnLogFile) throws IOException {
    this.txnLogFile = txnLogFile;
    createTxnInfoFile();
}

    @Override
public void createTxnInfoFile() throws IOException {
    File file = new File(txnLogFile);
    if (!file.exists()) {
        boolean directoryStructureCreated = file.getParentFile().mkdirs();
        logger.info("Directory structure created {} {} ", txnLogFile, directoryStructureCreated);
        boolean fileCreated = file.createNewFile();
        logger.info("txn log file created {} {} ", txnLogFile, fileCreated);
    }
    file = null;
}

The issue is that my first JUnit runs fine, but when i execute the 2nd junit the CsvService.createTxnInfoFile gets IOException

java.io.IOException: Access is denied
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)
    at dummy.name.service.impl.CsvServiceImpl.createTxnInfoFile(CsvServiceImpl.java:88)
    at dummy.name.service.impl.CsvServiceImpl.<init>(CsvServiceImpl.java:29)
    at dummy.name.service.impl.TransactionManagerImpl.<init>(TransactionManagerImpl.java:25)
    at dummy.name.service.TransactionManagerTest.beginTransactionTest_success(TransactionManagerTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:39)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:79)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:70)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

output

2019-04-22 08:40:28,895 [main] INFO  g.t.service.impl.CsvServiceImpl - Directory structure created data/test/tnx-log/tnc.log false 
2019-04-22 08:40:28,895 [main] INFO  g.t.service.impl.CsvServiceImpl - file.getAbsoluteFile() : C:\Users\jigar\apps\workspace\trade-publisher\data\test\tnx-log\tnc.log canWrite() : false
2019-04-22 08:40:28,895 [main] INFO  g.t.service.impl.CsvServiceImpl - txn log file created data/test/tnx-log/tnc.log true 

2019-04-22 08:40:28,957 [main] INFO  g.t.service.impl.CsvServiceImpl - Directory structure created data/test/tnx-log/tnc.log false 
2019-04-22 08:40:28,957 [main] INFO  g.t.service.impl.CsvServiceImpl - file.getAbsoluteFile() : C:\Users\jigar\apps\workspace\trade-publisher\data\test\tnx-log\tnc.log canWrite() : false


    @Override
    public void createTxnInfoFile() throws IOException {
        File file = new File(txnLogFile);
        if (!file.exists()) {
            boolean directoryStructureCreated = file.getParentFile().mkdirs();
            logger.info("Directory structure created {} {} ", txnLogFile, directoryStructureCreated);
            logger.info("file.getAbsoluteFile() : " + file.getAbsoluteFile() + " canWrite() : " + file.canWrite());
            boolean fileCreated = file.createNewFile();
            logger.info("txn log file created {} {} ", txnLogFile, fileCreated);
        }
        file = null;
    }
Jigar Naik
  • 1,946
  • 5
  • 29
  • 60
  • As the exception message say access to create the file has been denied. What is the actual file you want to create and where? – Progman Apr 22 '19 at 08:05
  • The `TransactionManager` is a service which saves trasnacitonStartTime,transactionEndTime, Status(SUCCESS/FAILURE) in csv format. I am trying to test this service. so both the test methods are writing to same CSV File, the TrasnacitonManager which invokes csv service perform read write operation on csv file, it also checks whether the csv file exist or not if it's not present in the path specified it will try to create it. – Jigar Naik Apr 22 '19 at 08:28
  • I've added the filepath in my original post. – Jigar Naik Apr 22 '19 at 08:29
  • I tried to perform `File file = new File(fileName);` operation in my @before setup() method but the result is same. – Jigar Naik Apr 22 '19 at 08:31
  • What is the full absolute path to the file and what does `canWrite()` return on the directory you are trying create the file in? – Progman Apr 22 '19 at 08:33
  • Possible duplicate of [Why is my program denying access to create a file?](https://stackoverflow.com/questions/15915349/why-is-my-program-denying-access-to-create-a-file) – Mebin Joe Apr 22 '19 at 08:34
  • here is the absolute path `C:\Users\jigar\apps\workspace\publisher\data\test\tnx-log\tnc.log` the path is correct and file does not exist. `canWrite()` returns false. – Jigar Naik Apr 22 '19 at 08:38
  • I have added logs in createTxnInfoFile and the output in original post. – Jigar Naik Apr 22 '19 at 08:45

1 Answers1

1

Issue resolved, instead of deleting and creating new file for every test. I am now deleting the content of file without deleting the actual file as below.

@After
public void tearDown() throws FileNotFoundException {
    this.transactionManager = null;
    PrintWriter writer = new PrintWriter(fileName);
    writer.print("");
    writer.close();
}
Jigar Naik
  • 1,946
  • 5
  • 29
  • 60