https://kotlinlang.org logo
#announcements
Title
# announcements
d

diegog

09/06/2017, 10:24 AM
Hi there does anyone know how to get the name of a function inside it?
k

karelpeeters

09/06/2017, 10:24 AM
What do you need it for?
There's some stacktrace trickery you can do but it's usually not a good idea.
d

diegog

09/06/2017, 10:26 AM
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

lovis

09/06/2017, 10:35 AM
you can use
elements = Throwable.getStackTrace()
and then use
elements[i].methodName
but actually : stackoverflow
a

arekolek

09/06/2017, 10:40 AM
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

christophsturm

09/06/2017, 10:43 AM
in junit there are better ways to get the current test
d

diegog

09/06/2017, 10:44 AM
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

christophsturm

09/06/2017, 1:04 PM
yes
i was not sure about the details but that seems to be one of the simplest solutions
2 Views