-2

I am calling a private method for testing and for that I am using the following code to invoke private method. repeat() is the private method of class Diamond

import org.junit.Test;
import static org.junit.Assert.*;
import java.lang.StringBuilder;
import java.lang.reflect.Method;
public class DiamondUnit {
        StringBuilder expect = new StringBuilder();
        Diamond test = new Diamond();
        Method m = test.getClass().getDeclaredMethod("repeat");
        m.setAccessible(true);
        m.invoke(test);

    @Test
        public void testRepeatNeg() {
            assertEquals("", test.repeat(expect,"a",-1));
        }
}

While compiling it is giving error

DiamondUnit.java:11: error: expected
m.setAccessible(true);
^
DiamondUnit.java:11: error: illegal start of type
m.setAccessible(true);
^
DiamondUnit.java:12: error: expected
m.invoke(test);
^
DiamondUnit.java:12: error: expected
m.invoke(test);
^

I had cop pasted the exact error message which I am getting

4

1 回答 1

1

您不能在方法块之外有语句。将代码放入适当的方法中。

import org.junit.Test;
import org.junt.SetUp;
import static org.junit.Assert.*;
import java.lang.StringBuilder;
import java.lang.reflect.Method;
public class DiamondUnit {
    public void method() {
        StringBuilder expect = new StringBuilder();
        Diamond test = new Diamond();
        Method m = test.getClass().getDeclaredMethod("repeat");
        m.setAccessible(true);
        m.invoke(test);
    }

    @Test
        public void testRepeatNeg() {
            assertEquals("", test.repeat(expect,"a",-1));
        }
}
于 2013-04-19T06:53:27.530 回答