ソースを参照

TraceUtils.getTestFrame

Ranides Atterwim 5 年 前
コミット
c8b34fdeac

+ 5 - 0
assira/src/main/java/net/ranides/assira/reflection/IClass.java

@@ -54,6 +54,11 @@ public interface IClass<T> extends IElement, Comparable<IClass<?>> {
     static <R> IClass<R> typeinfo(Class<R> type) {
         return IContext.DEFAULT.typeinfo(type);
     }
+
+    static IClass<?> typeinfo(StackTraceElement frame) {
+        return typeinfo(frame.getClassName());
+    }
+
     
     static IClass<?> typeinfo(String type) {
         try {

+ 38 - 0
assira/src/main/java/net/ranides/assira/trace/TraceUtils.java

@@ -6,6 +6,8 @@
  */
 package net.ranides.assira.trace;
 
+import net.ranides.assira.reflection.*;
+
 import java.util.List;
 import java.util.Optional;
 import java.util.function.Predicate;
@@ -119,4 +121,40 @@ public final class TraceUtils {
         return getName(2);
     }
 
+    /**
+     * Finds first public StackFrame invoked by JUnit framework.
+     * @return empty if code is not invoked from unit test
+     */
+    public static Optional<StackTraceElement> getTestFrame() {
+        List<StackTraceElement> frames = TraceUtils.getFrames();
+        int junit = -1;
+
+        // find first junit frame
+        for(int i=0, n=frames.size(); i<n; i++) {
+            if(frames.get(i).getClassName().startsWith("org.junit")) {
+                junit = i;
+                break;
+            }
+        }
+
+        // move back to first public frame
+        for(int i=junit-1; i>0; i--) {
+            StackTraceElement frame = frames.get(i);
+            IClass<?> type = IClass.typeinfo(frame.getClassName());
+
+            if(!type.isPublic()) {
+                continue;
+            }
+            if(type.name().startsWith("java.")) {
+                continue;
+            }
+            if(type.methods().require(IAttribute.PUBLIC).require(frame.getMethodName()).isEmpty()) {
+                continue;
+            }
+
+            return Optional.of(frame);
+        }
+        return Optional.empty();
+    }
+
 }

+ 10 - 0
assira/src/test/java/net/ranides/assira/trace/TraceUtilsTest.java

@@ -8,6 +8,8 @@ package net.ranides.assira.trace;
 
 import java.util.List;
 import static net.ranides.assira.junit.NewAssert.*;
+
+import net.ranides.assira.reflection.*;
 import net.ranides.assira.text.Wildcard;
 import org.junit.Test;
 
@@ -41,6 +43,14 @@ public class TraceUtilsTest {
     public void testFrame() {
         assertTrue( SI0.runFrame0() );
     }
+
+    @Test
+    public void verySimpleName() {
+        String actual = TraceUtils.getTestFrame()
+            .map(f -> IClass.typeinfo(f).shortname() +"."+ f.getMethodName())
+            .get();
+        assertEquals("TraceUtilsTest.verySimpleName", actual);
+    }
     
     private static final class SI0 {