For a Java class we are writing Data structure classes and we need to write a tester class to go with them. I am going for extra credit and trying to write a single tester class that I could either extend or pass a block to for use for any testing.
Is it possible to pass a block of code for a method to run? If this is not possible or practical, what is the best way to write a class so it can be extended?
–CODE–
package Lab1;
/**
* @author $RMDan
* @date 10-Sep-2012
* @class Tester
* @desc A Tester class for testing Java classes
* For use in Itec 251
*/
import java.io.*;
import java.util.*;
public class Tester {
//members
private String logS;
//Constructors
//Default to start == true
public Tester(){
this(true);
}
public Tester(Boolean start){
if(start == true){
this.start();
}
}
public final int start(){
int exit;
exit = test();
//this.displayLog();
this.exportLog("Test_Employee.Log");
return exit;
}
//Change the contents of this method to perform the test
private int test(){
return 0;
}
private void log(String message){
this.log(message,true);
}
private void log(String message, boolean display){
this.logS += message + "\n";
if(display==true){
System.out.println(message);
}
}
private void displayLog(){
System.out.print(this.logS);
}
private void exportLog(String file){
try{
String output = this.logS;
output = output.replaceAll("\n", System.getProperty("line.separator"));
try (BufferedWriter out = new BufferedWriter(new FileWriter(file + ".txt"))) {
out.write(output);
}
}
catch(IOException e){
System.out.println("Exception ");
}
}
}
Note: the final in the declaration of the start() method is there to shut up the compiler.
In java, “passing a block” is done by anonymous classes: on-the-fly implementations of an interface or class. You could use an existing interface like
Runnable, or create your own interface that returns a value, for example:then alter your code to expect one of these:
then to use it anonymously, call your start method with an anonymous MyTest:
You will definitely get more points for using anonymous classes!