Search code examples
javajunitassertfileinputstream

Using assertThrows while using Junit test for main method using FileInputStream


I am currently trying to use a JUnit test for my main method for the mastermind game. My input file contains an input with an illegal length for the input and I expect my main method to throw an exception somewhere down the line. How do I check that the exception is thrown during the execution of my main method? I have been trying to use the following code for this problem:

@Test
void testPlayErrors2() throws FileNotFoundException {
    String[] args= null;
    final InputStream original=System.in; 
    final InputStream fileIn= new FileInputStream(
        new File("playTest.txt"));
    System.setIn(fileIn);
    assertThrows(
               MastermindIllegalLengthException.class,
               () -> (Mastermind.main(args)),
               "Expected Mastermind.main() to throw MastermindIllegalLengthException, but it didn't"
        );
    
    System.setIn(original);
}

I get compilation errors on my use of assertthrows. I know exactly the line in my text file where the exception should be thrown so I would also be okay with being able to keep track of the input stream as in giving it one line at a time and then catching the exception where I expect it but I do not know how to do this.


Solution

  • You have to remove the parentheses from Mastermind.main(args):

    assertThrows(
      MastermindIllegalLengthException.class,
      () -> Mastermind.main(args),
      "Expected Mastermind.main() to throw MastermindIllegalLengthException, but it didn't"
    );
    

    I would also remove the message and use the standard error message of JUnit:

    assertThrows(
      MastermindIllegalLengthException.class,
      () -> Mastermind.main(args)
    );