tags:

views:

53

answers:

2

A program i am working on deals with processing file content. Right now i am writing jUnit tests to make sure things work as expected. As part of these tests, i'd like to reference an inline text file which would define the scope of a particular test.

How do i access such a file?

-- Let me clarify: Normally, when opening a file, you need to indicate where the file is. What i want to say instead is "in this project". This way, when someone else looks at my code, they too will be able to access the same file.I may be wrong, but isn't there a special way, one can access files which are a part of "this" project, relative to "some files out there on disk".

+2  A: 

If what you mean is you have a file you need your tests to be able to read from, if you copy the file into the classpath your tests can read it using Class.getResourceAsStream().

For an example try this link (Jon Skeet answered a question like this):

http://stackoverflow.com/questions/734671/read-file-in-classpath/734679#734679

Nathan Hughes
Excellent. Thank you.
mac
A: 

You can also implement your own test classes for InputStream or what have you.

package thop;

import java.io.InputStream;


/**
 *
 * @author tonyennis
 */
public class MyInputStream extends InputStream {

    private char[] input;
    private int current;

    public MyInputStream(String s) {
        input = s.toCharArray();
        current = 0;
    }

    public int read() {
        return (current == input.length) ? -1 : input[current++];
    }

    @Override
    public void close() {
    }
}

This is a simple InputStream. You give it a string, it gives you the string. If the code you wanted to test required an InputStream, you could use this (or something like it, heh) to feed exactly the strings wanted to test. You wouldn't need resources or disk files.

Here I use my lame class as input to a BufferedInputStream...

package thop;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author tonyennis
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        InputStream is = new MyInputStream("Now is the time");
        BufferedInputStream bis = new BufferedInputStream(is);
        int res;
        while((res = bis.read()) != -1) {
            System.out.println((char)res);
        }
    }
}

Now, if you want to make sure your program parses the inputStream correctly, you're golden. You can feed it the string you want to test with no difficulty. If you want to make sure the class being tested always closes the InputStream, add a "isOpen" boolean instance variable, set it to true in the constructor, set it to false in close(), and add a getter.

Now your test code would include something like:

MyInputStream mis = new MyInputStream("first,middle,last");
classBeingTested.testForFullName(mis);
assertFalse(mis.isOpen());
Tony Ennis