Search code examples
springscalascalatest

How do I integrate ScalaTest with Spring


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, but you get the gist).

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") {...}

Solution

  • 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") {...}
      }
    }