Skip to content

Instantly share code, notes, and snippets.

@shishkin
Created November 27, 2014 17:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shishkin/f3ce94fb601f63cdf1f5 to your computer and use it in GitHub Desktop.
Save shishkin/f3ce94fb601f63cdf1f5 to your computer and use it in GitHub Desktop.
Spring annotation-based configuration with ScalaTest
package samples
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest._
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation._
import org.springframework.stereotype.Service
import org.springframework.test.context.support.AnnotationConfigContextLoader
import org.springframework.test.context.{ActiveProfiles, ContextConfiguration, TestContextManager}
@RunWith(classOf[JUnitRunner])
class SpringContextTests extends FunSuite with SpringTest with Matchers {
@Autowired
val foo: FooService = null
test("wiring works") {
foo.foo should be("test")
}
}
@ContextConfiguration(
classes = Array(classOf[TestConfig], classOf[ProdConfig]),
loader = classOf[AnnotationConfigContextLoader])
@ActiveProfiles(Array("test"))
trait SpringTest extends BeforeAndAfterEach { this: Suite =>
override def beforeEach(): Unit = {
new TestContextManager(classOf[SpringTest]).prepareTestInstance(this)
super.beforeEach()
}
}
@Configuration
@Profile(Array("test"))
class TestConfig {
@Bean
def foo: FooService = new FooMock
}
@ComponentScan(basePackages = Array("samples"))
@Configuration
@Profile(Array("prod"))
class ProdConfig {
}
trait FooService {
def foo: String
}
@Service
class Foo extends FooService {
override def foo = "bar"
}
class FooMock extends FooService {
override def foo = "test"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment