private void detectLeaks() { if (skipLeakDetectionReason != null) { CanaryLog.d("Skipping leak detection because the test %s", skipLeakDetectionReason); skipLeakDetectionReason = null; return; } InstrumentationLeakDetector leakDetector = new InstrumentationLeakDetector(); InstrumentationLeakResults results = leakDetector.detectLeaks(); reportLeaks(results); }
private void assertLeak(Class<?> expectedLeakClass) { InstrumentationLeakDetector leakDetector = new InstrumentationLeakDetector(); InstrumentationLeakResults results = leakDetector.detectLeaks(); if (results.detectedLeaks.size() != 1) { throw new AssertionError( "Expected exactly one leak, not " + results.detectedLeaks.size() + resultsAsString( results.detectedLeaks)); } InstrumentationLeakResults.Result firstResult = results.detectedLeaks.get(0); String leakingClassName = firstResult.analysisResult.className; if (!leakingClassName.equals(expectedLeakClass.getName())) { throw new AssertionError( "Expected a leak of " + expectedLeakClass + ", not " + leakingClassName + resultsAsString( results.detectedLeaks)); } }
@Test public void detectsLeak() { leaking = new Date(); RefWatcher refWatcher = LeakCanary.installedRefWatcher(); refWatcher.watch(leaking); InstrumentationLeakDetector leakDetector = new InstrumentationLeakDetector(); InstrumentationLeakResults results = leakDetector.detectLeaks(); if (results.detectedLeaks.size() != 1) { throw new AssertionError("Expected exactly one leak, not " + results.detectedLeaks.size()); } InstrumentationLeakResults.Result firstResult = results.detectedLeaks.get(0); String leakingClassName = firstResult.analysisResult.className; if (!leakingClassName.equals(Date.class.getName())) { throw new AssertionError("Expected a leak of Date, not " + leakingClassName); } } }