本文介绍了如何将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") {...}
  }
}

这篇关于如何将ScalaTest与Spring集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 18:44