Spring
[Spring] java.lang.reflect.Method 테스트 해보기
티-스토리
2012. 11. 6. 23:09
-- 입력받는 파라미터가 없는 메서드
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import java.lang.reflect.Method;
import org.junit.Test;
public class ReflectTest {
@Test
public void testReflect() throws Exception {
Method method = Sample.class.getMethod("getSample");
assertThat((String) method.invoke(Sample.class.newInstance()), is("Sample"));
}
public static class Sample {
public String getSample() {
return "Sample";
}
public String getSample(String append) {
return "Sample " + append;
}
}
}
-- 파라미터를 입력받는 메서드
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import java.lang.reflect.Method;
import org.junit.Test;
public class ReflectTest {
@Test
public void testReflect() throws Exception {
Method method = Sample.class.getMethod("getSample");
assertThat((String) method.invoke(new Sample()), is("Sample"));
method = Sample.class.getMethod("getSample", String.class);
assertThat((String)method.invoke(new Sample(), "Test"), is("Sample Test"));
}
public class Sample {
public String getSample() {
return "Sample";
}
public String getSample(String append) {
return "Sample " + append;
}
}
}
-- 다수의 파라미터를 받는 메서드
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import java.lang.reflect.Method;
import org.junit.Test;
public class ReflectTest {
@Test
public void testReflect() throws Exception {
Method method = Sample.class.getMethod("getSample");
assertThat((String) method.invoke(new Sample()), is("Sample"));
method = Sample.class.getMethod("getSample", String.class);
assertThat((String)method.invoke(new Sample(), "Test"), is("Sample Test"));
method = Sample.class.getMethod("getSample", String.class, int.class);
assertThat((String)method.invoke(new Sample(), "Cut", 7), is("Cut"));
}
public class Sample {
public String getSample() {
return "Sample";
}
public String getSample(String append) {
return "Sample " + append;
}
public String getSample(String append, int beginIndex){
return getSample(append).substring(beginIndex);
}
}
}