0

I have a following save method, but I dont know how to verify this method. How can i verify it in JUnit ??

public static void save(Spiel spielen,File file ) {
    try(ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(file))) {

        out.writeObject(spielen);

        System.out.println("Speichern Erfolgreich");
        System.out.println();
    }
    catch (Exception  e) {
        System.out.println("Fehler beim Speichern");
        System.out.println();
    }
}
  • Possible duplicate of [Comparing text files with Junit](https://stackoverflow.com/questions/466841/comparing-text-files-with-junit) – vlumi Jun 10 '19 at 05:37
  • Remember that you can not test a flow which it contains an initialization with "new" statement. – Emre Savcı Jun 10 '19 at 05:40
  • @EmreSavcı that is simply not true. One could pass in the name of a temp file and write to the real file system. Or use powermock (don't do that) to mock new(). – GhostCat Jun 10 '19 at 05:53
  • 2
    Unrelated: don't just print "error happened"! At least include the exception. You are throwing away all knowledge about the error that happened here. – GhostCat Jun 10 '19 at 05:54
  • @vlumi he serializes to binary. That is a bad start to duplicate with "how to compare text files"! – GhostCat Jun 10 '19 at 06:14
  • @GhostCat The accepted answer there supports binary files, too – vlumi Jun 10 '19 at 06:58
  • @vlumi that is not at all obvious. And it adds another dependency. – GhostCat Jun 10 '19 at 07:00
  • @GhostCat then it would be integration test, not unit test. – Emre Savcı Jun 10 '19 at 07:04
  • @EmreSavcı I don't see requirements that the test would need to be a unit test? I do like pure functions like anyone else, but sticking to it does complicate file output tests like this. – vlumi Jun 10 '19 at 07:06

2 Answers2

1

One simple solution: don't pass in a file object. But instead a factory that creates an OutputStream for you.

At runtime, this could be a FileOutputStream. But for testing, you could pass a different factory that creates, say a ByteArrayOutputStream. Then your code writes to memory without knowing it.

And then you could write another test that reads back these bytes.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

You can store the reference, expected output file on the disk, and then compare the tested output against that. There are many ways to do that comparison, including some JUnit Addons (its FileAssert in particular), or just read both files into byte arrays and assert that they equal.

Many other utilities exist, some listed on this answer: File comparator utilities

vlumi
  • 1,321
  • 1
  • 9
  • 18