damon
damon

Reputation: 8477

how to unittest a java method when data is created inside the constructor

I have a class which exposes a set of apis as below

class MyDataProcessor{    
    private int M;
    private double[] data;

    public MyDataProcessor(int N,int M){
        this.M = M;
        this.data = new double[M];
        for(int i=0;i<M;i++){
            int randomX = //get a random value
            double v = processValue(randomX);
            this.data[i] = v;
        }
    private static double processValue(int randomX){
         //do some work on randomX and return a double value
    }

    private double mean(double[] a){
        double meanValue = //find mean of a
        return meanValue;
    }

    private double stddev(double[] a){
        double stdDevValue = //find stddev of a
        return stdDevValue;
    }

    public double lowerBoundConf(){
        double mean = mean(this.data);
        double sd = stddev(this.data);
        double lb = mean + (1.96*stddev)/Math.sqrt(this.M);
        return lb;
    }
}

Here,I have to unit test the method lowerBoundConf.I cannot provide a double[] array to this method(that would have made it simple).The array has to come from inside the constructor.I cannot figure out how I can write tests for this.Can someone help?

Upvotes: 0

Views: 58

Answers (2)

Arne Burmeister
Arne Burmeister

Reputation: 20604

For testing any functionality of your class you need to access the data array. Make the field package protected final to test the methods against the data values.

But why test calculations on unknown random data? This is useless (homework?) and also only random result.

Upvotes: 2

Philipp Sander
Philipp Sander

Reputation: 10249

Testing methods that deal with random is always hard.

But you can still test the whole class. You have expect something from that method when you give here specific parameters and thats how your tests should look like.

When you don't know the concrete values that are returned test some information around that like min/max.

An other alternativ would be using Mock frameworks like Mockito which is pretty hard inyour case because all but one methods are private

Upvotes: 1

Related Questions