Embedded Unit Testing
A simpler way to write tests, embedded. This is rife with possibilities and usefulness.
More on it later...I have to run.
import java.util.*;
import junit.framework.*;
/** Creates moving average of double data, everytime new data is added */
public class MovingAverage {
private int setSize = 1; // Size of set
private LinkedList set = new LinkedList();
private double average = 0.0;
/** Create moving average of size data elements */
public MovingAverage(int size) {
setSize = size;
}
/** Add's data to the set, returns the moving average, 0.0 is returned when there are not sufficient data */
public double add(double data) {
set.add(new Double(data));
if(set.size() <= setSize) {
average = (average * (set.size() - 1) + data) / set.size();
} else {
double firstData = ((Double) set.remove(0)).doubleValue();
average += (data - firstData) / setSize;
}
return average;
}
public static void main(String args[]) {
junit.textui.TestRunner.run(new TestSuite(MovingAverage.TestMovingAverage.class));
}
public static class TestMovingAverage extends TestCase {
public TestMovingAverage(String name) {
super(name);
}
public void testAddFirstSetSizeMinusOneValues() {
int size = 2000;
MovingAverage avg = new MovingAverage(size);
for(int i = 0;i < size - 1;i++) {
assertEquals("First N Values of Moving Average (Set Size > N), N = " + (i + 1), i/2.0, avg.add(i), 0.001);
}
}
public void testAddMovingAverage() {
int size = 200;
MovingAverage avg = new MovingAverage(size);
for(int i = 1;i < size;i++) {
avg.add(i);
}
for(int i = size;i < size * size;i++) {
assertEquals("Testing moving average for 1..." + i, (1.0 + 2 * i - size)/2, avg.add(i), 0.001);
}
}
}
}
<< Home