1 package leakcanary
2 
3 import org.assertj.core.api.Assertions.assertThat
4 import org.junit.BeforeClass
5 import org.junit.Rule
6 import org.junit.Test
7 import org.junit.rules.RuleChain
8 import org.junit.rules.TestRule
9 import org.junit.runner.Description
10 import org.junit.runners.model.Statement
11 
12 class TestDescriptionHolderTest {
13 
14   companion object {
15     var beforeClassThrowable: Throwable? = null
16 
beforeClassnull17     @BeforeClass @JvmStatic fun beforeClass() {
18       beforeClassThrowable = try {
19         TestDescriptionHolder.testDescription
20         null
21       } catch (throwable: Throwable) {
22         throwable
23       }
24     }
25   }
26 
27   class AttemptsRetrievingTestDescription : TestRule {
28 
29     var beforeEvaluateThrowable: Throwable? = null
30 
applynull31     override fun apply(base: Statement, description: Description): Statement {
32       return object : Statement() {
33         override fun evaluate() {
34           beforeEvaluateThrowable = try {
35             TestDescriptionHolder.testDescription
36             null
37           } catch (throwable: Throwable) {
38             throwable
39           }
40           base.evaluate()
41         }
42       }
43     }
44   }
45 
46   private val outerRule = AttemptsRetrievingTestDescription()
47   private val innerRule = AttemptsRetrievingTestDescription()
48 
49   @get:Rule
50   val rule = RuleChain.outerRule(outerRule).around(TestDescriptionHolder).around(innerRule)!!
51 
52   @Test
retrievingTestDescriptionDoesNotThrowWhileTestEvaluatingnull53   fun retrievingTestDescriptionDoesNotThrowWhileTestEvaluating() {
54     TestDescriptionHolder.testDescription
55   }
56 
57   @Test
currentTestDescriptionIsAccuratenull58   fun currentTestDescriptionIsAccurate() {
59     val stackTop = RuntimeException().stackTrace.first()
60     val testDescription = TestDescriptionHolder.testDescription
61     assertThat(testDescription.className).isEqualTo(stackTop.className)
62     assertThat(testDescription.methodName).isEqualTo(stackTop.methodName)
63   }
64 
65   @Test
testDescriptionThrowsBeforeClassnull66   fun testDescriptionThrowsBeforeClass() {
67     // On API 16, assertThat(Throwable) causes a TypeComparators class init failure.
68     assertThat(beforeClassThrowable == null).isFalse()
69   }
70 
71   @Test
testDescriptionThrowsBeforeOuterEvaluatenull72   fun testDescriptionThrowsBeforeOuterEvaluate() {
73     // On API 16, assertThat(Throwable) causes a TypeComparators class init failure.
74     assertThat(outerRule.beforeEvaluateThrowable == null).isFalse()
75   }
76 
77   @Test
testDescriptionDoesNotThrowBeforeInnerEvaluatenull78   fun testDescriptionDoesNotThrowBeforeInnerEvaluate() {
79     // On API 16, assertThat(Throwable) causes a TypeComparators class init failure.
80     assertThat(innerRule.beforeEvaluateThrowable == null).isTrue()
81   }
82 }
83