Skip to content

Commit 7872b6d

Browse files
authored
Merge pull request #213 from einholen/fix-unclosed-mocking-session
Close mocking session on aborted Scalatest runs
2 parents 1e563d3 + aee9010 commit 7872b6d

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

core/src/main/scala/org/mockito/MockitoScalaSession.scala

+6
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ class MockitoScalaSession(name: String, strictness: Strictness, logger: MockitoS
2020

2121
Mockito.framework().addListener(listener)
2222

23+
/**
24+
* If the test has thrown an exception, the session will check first if the exception could be related to a misuse
25+
* of mockito. If not, it will rethrow the original error so the real test failure can be reported by the testing framework
26+
*
27+
* @param t exception thrown by the test framework
28+
*/
2329
def finishMocking(t: Option[Throwable] = None): Unit = {
2430
listener.cleanLenientStubs()
2531
try t.fold {

scalatest/src/main/scala/org/mockito/scalatest/MockitoSessionFixture.scala

+14-10
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
11
package org.mockito.scalatest
2+
23
import org.mockito.{ MockitoScalaSession, Strictness }
34
import org.scalatest._
45

5-
import scala.util.control.NonFatal
6-
76
private[mockito] trait MockitoSessionFixture extends TestSuite { this: Suite =>
87

98
val strictness: Strictness = Strictness.StrictStubs
109

1110
abstract override def withFixture(test: NoArgTest): Outcome = {
1211
val session = MockitoScalaSession(name = s"${test.name} - session", strictness)
13-
val result = super.withFixture(test)
14-
// if the test has thrown an exception, the session will check first if the exception could be related to a mis-use
15-
// of mockito, if not, it will throw nothing so the real test failure can be reported by the ScalaTest
12+
13+
val result =
14+
try {
15+
super.withFixture(test)
16+
} catch {
17+
case t: Throwable =>
18+
session.finishMocking(Some(t))
19+
throw t
20+
}
21+
1622
session.finishMocking(result.toOption)
1723
result
1824
}
@@ -25,15 +31,13 @@ private[mockito] trait MockitoSessionAsyncFixture extends AsyncTestSuite { this:
2531
abstract override def withFixture(test: NoArgAsyncTest): FutureOutcome = {
2632
val session = MockitoScalaSession(name = s"${test.name} - session", strictness)
2733

28-
// if the test has thrown an exception, the session will check first if the exception could be related to a mis-use
29-
// of mockito, if not, it will throw nothing so the real test failure can be reported by the ScalaTest
3034
val result =
3135
try {
3236
super.withFixture(test)
3337
} catch {
34-
case NonFatal(ex) =>
35-
session.finishMocking(Some(ex))
36-
throw ex
38+
case t: Throwable =>
39+
session.finishMocking(Some(t))
40+
throw t
3741
}
3842

3943
result.onOutcomeThen(o => session.finishMocking(o.toOption))

0 commit comments

Comments
 (0)