0

I have a method that creates a file if it doesn't exist and if it does exist performs some other methods and appends to this file after. I was wondering how can I write tests for this? I've looked online and it seems to say that mocking a file is a bad idea (In all honesty I'm not too sure how this would help) .

Is there a way to brute force the test to hit the if statement. I remembered you can stub results in but I wasn't sure if you could force a function to hit certain conditionals. I was thinking if we can force it to hit a conditional then I would be able to use verify to make sure my SingleLineWriter method only runs once? Then the same but for the else and to make sure it only runs BalanceAppender once?

public void ManageAccount(String name) {

    try {
        File myObj = new File(name + ".txt");

        if (myObj.createNewFile()) {
            File myTransactionObj = new File(name + "Transactions.txt");
            myTransactionObj.createNewFile();
            // If File doesn't exist creates name.txt with 0 balance
            writer.SingleLineWriter(name, "0");
        } else {
            account.setName(name);
            String line = reader.SingleLineRead(name);

            double balance = Double.parseDouble(line);

            double newBalance = ManageBank(balance);

            writer.BalanceAppender(newBalance, name);

        }

    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }

}
  • One way would be to inject `myObj` to the method instead of creating it inside, so during a test you can mock the behavior of `createNewFile` – leberknecht May 12 '21 at 09:15
  • How would I do that? Create a mock file at the top of my test class and then @InjectMocks? And then following on how would I actually mock the behaviour of it? I'm new to Mockito so apologies if these are all silly questions. – Connor Gill May 12 '21 at 09:22
  • Not sure tbh, im not familiar with java, but https://stackoverflow.com/questions/16243580/mockito-how-to-mock-and-assert-a-thrown-exception could help maybe? – leberknecht May 12 '21 at 11:45

0 Answers0