简体   繁体   中英

Writing a class so it can be extended or passing blocks JAVA

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.

Overkill time: have a look at JUnit , a test framework used in many real-life applications. It is designed to make it easy to implement tests. A typical test may be as small as this:

import org.junit.*;
import org.junit.assert.*;
public class NameOfClassToTest {
    @Test public void nameOfSpecificTest() {
        // logic to calculate 'expected' and 'result'
        // actual example test
        assertTrue(expected.equals(result));
    }
}

And can be command-line executed with this:

java org.junit.runner.JUnitCore TestClass1 [...other test classes...]

(Although your IDE probably includes in-built support for JUnit tests).

As a teacher, I would be much more impressed if you implement a JUnit test than if you build your own testing framework from scratch...

"Passing a block of code" is the same as passing a reference to an object with a known method (ie interface). eg :

public class Tester {
  public static void testSomeCodeBlock(Runnable codeBlock) {
    codeBlock.run();
  }
}

Tester.testSomeCodeBlock(new Runnable() {
  @Override public void run() {
    System.out.println("my code block");
  }
});

Alternately, if you wanted to use extension, you would have to make your Tester.test() method protected (and probably abstract) so the test implementations could override it.

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:

interface MyTest {
    int test();
}

then alter your code to expect one of these:

public final int start(MyTest myTest) {
    ...
    exit = myTest.test();
    ...
}

then to use it anonymously, call your start method with an anonymous MyTest:

start(new MyTest() {
    public int test() {
        // do something
    } 
})l


You will definitely get more points for using anonymous classes!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM