diff --git a/tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs b/tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs index e74745ec73e..e2228c6fd3d 100644 --- a/tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs +++ b/tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs @@ -510,14 +510,30 @@ public void DoNotLeakWeakReferences () Assert.IsTrue (surfaced.All (s => s.Target != null), "#1"); + // `Runtime.GetSurfacedObjects()` is process-global: NUnit/MTP + // infrastructure (per-test TestExecutionContext, listeners, Console + // capture, etc.) creates and releases transient Java.Lang.Object + // peers around every test, so the count drifts by a few entries + // between the snapshots below. Allow a small tolerance instead of + // requiring an exact count -- a real leak would dwarf this. + const int tolerance = 10; + WeakReference r = null; + Exception threadException = null; var t = new Thread (() => { - var c = new MyCb (); - Assert.AreEqual (startCount + 1, Runtime.GetSurfacedObjects ().Count, "#2"); - r = new WeakReference (c); + try { + var c = new MyCb (); + Assert.That (Runtime.GetSurfacedObjects ().Count, + Is.EqualTo (startCount + 1).Within (tolerance), "#2"); + r = new WeakReference (c); + } catch (Exception e) { + threadException = e; + } }); t.Start (); t.Join (); + if (threadException != null) + throw new Exception ("Worker thread failed", threadException); GC.Collect (); GC.WaitForPendingFinalizers (); @@ -525,7 +541,7 @@ public void DoNotLeakWeakReferences () GC.WaitForPendingFinalizers (); surfaced = Runtime.GetSurfacedObjects (); - Assert.AreEqual (startCount, surfaced.Count, "#3"); + Assert.That (surfaced.Count, Is.EqualTo (startCount).Within (tolerance), "#3"); Assert.IsTrue (surfaced.All (s => s.Target != null), "#4"); } }