-1

I'm refactoring spring boot tests creating encapsulated classes with common behavior that will be injected in other tests. This classes has scope only in test package.

Spring ignore slices that will not be used in test (which is great and by design of spring boot test 1.5), but also ignore any @Component in src/test/java.

Question is how to configure spring boot test to pickup components in test/java?

I have one incomplete solution, that works for one test My current solution is:

import com.example.testClasses.TestUtil;

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(TestConfiguration.class)
public class ExampleTest {

  @SpyBean
  private ServiceDependency1 service1;

  @Autowired
  private TestUtil testUtil;

}

@Configuration
@ComponentScan(basePackages = "com.example.testClasses")
public class TestConfiguration {



}

@Component
public class TestUtil {

   public TestUtil(ServiceDependency1 service) {
   }
}

The solution above partial works, when another Utils is added TestUtils2 with different injection dependencies, this dependencies are not resolved.

That is because dependency for TestUtil1 is only solved with the @SpyBean, this is not the case in second test.

Giovanni Silva
  • 705
  • 5
  • 17

1 Answers1

0

I put the all SpyBean on the TestConfiguration and use @AutoWired for each test.

import com.example.testClasses.TestUtil;

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(TestConfiguration.class)
public class ExampleTest {

  @Autowired
  private ServiceDependency1 service1;

  @Autowired
  private TestUtil testUtil;

}

@Configuration
@ComponentScan(basePackages = "com.example.testClasses")
public class TestConfiguration {

    @SpyBean
    private ServiceDependency1 service1

    @SpyBean
    private ServiceDependency2 service2

}

@Component
public class TestUtil {

   public TestUtil(ServiceDependency1 service) {
   }
}
Giovanni Silva
  • 705
  • 5
  • 17