Pages

Testing Spring autowiring with JUnit

Given a Spring component, we can let Spring wiring it automatically to a reference to an interface that it implements, assuming that we tell Spring which components to scan. And using the SpringJUnit4ClassRunner we can test if it works.

In my Maven Boot Spring web application, I created a package, dd.sia.soundsystem, and I put in it an interface:
public interface CompactDisc {
    String play();
}
Then I have written a class that implements it, annotated as Spring component:
@Component
public class SgtPeppers implements CompactDisc {
    // ...
    @Override
    public String play() {
        // ...
    }
}
Now I create a class having the only purpose of letting know to Spring how to configure for autowiring:
@Configuration
@ComponentScan(basePackageClasses=CompactDisc.class)
public class CDPlayerConfig { 
}
Here I said that Spring has to scan all the classes based on CompactDisc. There are other ways to feed the annotation ComponentScan, and we could even rely on a empty default, meaning check all the components in the current package. I feel more confident passing the base class/interface.

Let's test if the wiring works correctly.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
    @Autowired
    private CompactDisc cd;

    @Test
    public void testNotBeNull() {
        assertNotNull(cd);
    }

    @Test
    public void testPlay() {
        assertEquals("Sgt. Pepper's Lonely Hearts Club Band by The Beatles", cd.play());
    }
}
I annotated the class to let JUnit know that it should use the specific Spring runner, then I said to Spring that it should configure the context using CDPlayerConfig. Now I just have to autowire a CompactDisc reference, and let Spring inject in it an instance of the only available component rooted in it, namely, the SgtPeppers class.


I have written this post while reading the second chapter, Wiring beans, of Spring in Action, Fourth Edition by Craig Walls. While doing it, I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of using the classic xml configuration.

Full code on github. Most relevant files are the ones in the source soundsystem package and the test file.

No comments:

Post a Comment