如何将ScalaTest与Spring集成

如何将ScalaTest与Spring集成

问题描述:

我需要使用Spring上下文中的@Autowired字段填充我的ScalaTest测试,但是大多数Scalatest测试(例如FeatureSpec不能由SpringJUnit4ClassRunner.class-

I need to populate my ScalaTest tests with @Autowired fields from a Spring context, but most Scalatest tests (eg FeatureSpecs can't be run by the SpringJUnit4ClassRunner.class -

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="myPackage.UnitTestSpringConfiguration", loader=AnnotationConfigContextLoader.class)
public class AdminLoginTest {
    @Autowired private WebApplication app;
    @Autowired private SiteDAO siteDAO;

(Java,但您掌握了要点).

(Java, but you get the gist).

如何为ScalaTest从ApplicationContext填充@Autowired字段?

How do I populate @Autowired fields from an ApplicationContext for ScalaTest?

class AdminLoginFeatureTest extends FeatureSpec with GivenWhenThen with ShouldMatchersForJUnit {

  @Autowired val app: WebApplication = null
  @Autowired val siteDAO: SiteDAO = null

  feature("Admin Login") {
    scenario("Correct username and password") {...}

使用TestContextManager,因为这会缓存上下文,这样就不会在每次测试时都重新构建它们.它是通过类注释配置的.

Use the TestContextManager, as this caches the contexts so that they aren't rebuilt every test. It is configured from the class annotations.

@ContextConfiguration(
  locations = Array("myPackage.UnitTestSpringConfiguration"), 
  loader = classOf[AnnotationConfigContextLoader])
class AdminLoginFeatureTest extends FeatureSpec with GivenWhenThen with ShouldMatchers {

  @Autowired val app: WebApplication = null
  @Autowired val siteDAO: SiteDAO = null
  new TestContextManager(this.getClass()).prepareTestInstance(this)

  feature("Admin Login") {
    scenario("Correct username and password") {...}
  }
}