简体   繁体   中英

Get a reference of an object using class name Java

I'm Running a method annotated with @Test and I want get a reference to the object JunitCore , this object invokes the method by reflection.

How can I get a reference to the that object, If It's possible?(maybe a security issue)

I tried reflection and classLoader but I couldn't make it work.

Thanks

The JUnitCore is a basic entry point for Junit tests. The way it works is it finds a List of classes provided as java command arguments and uses them to create a Runner with which it runs the test cases.

At no point during processing does the main method in JUnitCore ever pass a reference of the JUnitCore instance it creates to any other object. As such, it is not retrievable either directly or with reflection.

JUnitCore is as follows

public static void main(String... args) {
    runMainAndExit(new RealSystem(), args);
}

public static void runMainAndExit(JUnitSystem system, String... args) {
    Result result= new JUnitCore().runMain(system, args);
    system.exit(result.wasSuccessful() ? 0 : 1);
}

public Result runMain(JUnitSystem system, String... args) {
    system.out().println("JUnit version " + Version.id());
    List<Class<?>> classes= new ArrayList<Class<?>>();
    List<Failure> missingClasses= new ArrayList<Failure>();
    for (String each : args)
        try {
            classes.add(Class.forName(each));
        } catch (ClassNotFoundException e) {
            system.out().println("Could not find class: " + each);
            Description description= Description.createSuiteDescription(each);
            Failure failure= new Failure(description, e);
            missingClasses.add(failure);
        }
    RunListener listener= new TextListener(system);
    addListener(listener);
    Result result= run(classes.toArray(new Class[0]));
    for (Failure each : missingClasses)
        result.getFailures().add(each);
    return result;
}

... // and more

No where in this implementation is a reference to this passed as an argument. As such, you cannot get a reference to it.

The only way is to create a JunitCore instance and run the tests yourself:

JUnitCore junit = new JUnitCore();
//we can add a listener to listen for events as we run the tests
junit.addListener(new RunListener(){

    @Override
    public void testFailure(Failure failure) throws Exception {
    System.out.println("failed " + failure);
    }


});
Result result = junit.run(Class.forName(nameOfTestSuite));

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