I'm writing a unit test suite for a Scala Play application and I'm wondering if there's anything analogous to java's
@Mock
private Foo foo;
@Autowired/InjectMocks
private Bar fixture;
@BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
For auto-mocking the annotated class and resetting it after every test
Currently I'm settling for
TestClass extends PlaySpec with BeforeAndAfterEach
private val foo = mock[Foo]
override def fakeApplication(): Application =
new GuiceApplicationBuilder().overrides(bind[Foo].toInstance(foo)).build
override protected def beforeEach(): Unit = {
reset(foo)
}
A cursory attempt at using the java annotations in the scala test was not successful. My current approach works, I just want to make sure there's not a nicer one.
mockito-scala solves this problem from version 0.1.1, as it provides a trait (org.mockito.integrations.scalatest.ResetMocksAfterEachTest
) that helps to automatically reset any existent mock after each test is run
The trait has to be mixed after org.mockito.MockitoSugar
in order to work, otherwise your test will not compile
So your code would look like this
TestClass extends PlaySpec with MockitoSugar with ResetMocksAfterEachTest
private val foo = mock[Foo]
override def fakeApplication(): Application =
new GuiceApplicationBuilder().overrides(bind[Foo].toInstance(foo)).build
The main advantage being not having to remember to manually reset each one of the mocks...
If for some reason you want to have a mock that is not reset automatically while using this trait, then it should be
created via the companion object of org.mockito.MockitoSugar
so is not tracked by this mechanism
Disclaimer: I'm a developer of that library