Home > Blockchain >  Spock Test to Check that a Java Program has Indeed Extracted a Specific File Extension
Spock Test to Check that a Java Program has Indeed Extracted a Specific File Extension

Time:09-30

I wrote the following program that successfully extracts a .json file. I want to check with Spock and Groovy that my method, indeed extracts a file with the .json extension. At the end of the question you can see the stack trace. I am completely new to testing and I am definitely missing the picture here as I am little bit confused. Any advice that you can provide me?

TEST CLASS SO FAR

    def "Json file is returned"(){
        given:
        JsonFile jsonFile = new JsonFile()
        String filename = "items.json"

        when:
        jsonFile.writingTheFile()
        String str = ""
        BufferedWriter writer = new BufferedWriter(new FileWriter("./items.json"))
        writer.write(str)

        then:
        str == filename
    }

CLASS TO TESTED

package inventory;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonFile extends TrackingFile {

    public JsonFile(ArrayList<Item> items) {
        super(items);
    }

    static String json = "";
    static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().serializeNulls().setPrettyPrinting()
            .setVersion(1.0).create();

    @Override
    void createTheFile() {
        json = gson.toJson(super.items);
        System.out.println(json);

    }

    @Override
    void writingTheFile() throws IOException {
        String str = json;
        BufferedWriter writer = new BufferedWriter(new FileWriter("./items.json"));
        writer.write(str);
        writer.close();

    }

}

ABSTRACT CLASS THAT GETS EXTENDED TO THE TESTED CLASS

package inventory;

import java.io.IOException;
import java.util.ArrayList;

public abstract class TrackingFile {

    protected ArrayList<Item> items;

    public TrackingFile(ArrayList<Item> items) {
        this.items = items;
    }

    abstract void createTheFile() throws IOException;

    abstract void writingTheFile() throws IOException;

}

I am receiving the following stack trace: Stack Trace Picture

CodePudding user response:

Something to get going with, I didn't know what your Item class was so substituted for String in this example.

You might want to make the path configurable so you can write to different places in tests etc, you also might want to check if the file already exists at the start of the test and remove it and/or remove it at the end of the test.

def "Json file is returned"(){
    given:
        JsonFile jsonFile = new JsonFile(['one', 'two'])
    when:
        jsonFile.createTheFile()
        jsonFile.writingTheFile()
    then:
        Files.exists(Paths.get("items.json"))
}
  • Related