Skip to content

Instantly share code, notes, and snippets.

@lidaling
Forked from shishkin/SpringContextTests.scala
Created September 1, 2017 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lidaling/c7245829ba9f6a2c418f673afec14700 to your computer and use it in GitHub Desktop.
Save lidaling/c7245829ba9f6a2c418f673afec14700 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