Hi there does anyone know how to get the name of a...
# announcements
d
Hi there does anyone know how to get the name of a function inside it?
k
What do you need it for?
There's some stacktrace trickery you can do but it's usually not a good idea.
d
I'm writing a selenium test and I would like to take the screenshot when things go wrong hence I would like to name the screenshot file as the classname+methodname.jpg
l
you can use
elements = Throwable.getStackTrace()
and then use
elements[i].methodName
but actually : stackoverflow
a
Copy code
package com.example

class Foo {
    fun bar() {
        Thread.currentThread().stackTrace[1].let {
            println("${it.className}.${it.methodName}()")
        }
    }
}

fun main(arg: Array<String>) {
    Foo().bar()
}
prints:
com.example.Foo.bar()
c
in junit there are better ways to get the current test
d
Ah! for example?
otherwise I can stick to @arekolek solution (thanks for that)
import org.junit.Rule; public class NameRuleTest { @Rule public TestName name = new TestName(); @Test public void testA() { assertEquals("testA", name.getMethodName()); } @Test public void testB() { assertEquals("testB", name.getMethodName()); } }
@christophsturm you mean something like that?
c
yes
i was not sure about the details but that seems to be one of the simplest solutions