scala - Using ScalaTest to test java that contain @Autowired and private fields -
i have begun use scalatest test java code , (i've read "testing in scala" book).
recently i've been trying test java spring code contain fields marked private
, @autowired
. there no setter methods these fields.
i realise test them using junit + mockito using annotations @injectmocks
, @mock
, however, test them using scalatest , mocking framework (such mockito or scalamock).
my question: can scalatest + mockito used mock out private fields or these frameworks require java classes have public
setter method defined private
+ @autowired
fields?
you can injectmocks. here's working example using scalatest , mockito test class containing @autowired members:
import org.mockito.{mockitoannotations, injectmocks, mock} import org.scalatest.{funspec, beforeandafter} import org.scalatest.matchers._ import org.mockito.mockito._ import org.springframework.beans.factory.annotation.autowired class injectmocksspec extends funspec beforeandafter { @mock var parammock: mockedclass = null @injectmocks var testclass = new testclass() describe("injectmocks") { it("should inject mock autowired field") { mockitoannotations.initmocks(this) when(parammock.get).thenreturn("bar") testclass.test should be("bar") verify(parammock, times(1)).get } } } class mockedclass { def get: string = { "foo" } } class testclass { @autowired var param: mockedclass = null def test: string = { param.get } }
Comments
Post a Comment