Pages

Testing Spring autowiring in a more complex scenario

Let's improve the code seen in the previous Spring post. I add a CD player components that implements a media player interface and it is autowired to the CD component.

The media player interface has just a couple of methods
public interface MediaPlayer {
    String play();
    boolean hasMedia();
}
The second one checks if a media is inserted in the player and, you have probably guessed, it's there just to let me check if the autowiring of a CD is done as expected.

Then I have written a CD player, implementing this interface
@Component
public class CDPlayer implements MediaPlayer {
    private CompactDisc cd;

    @Autowired
    public CDPlayer(CompactDisc cd) {
        this.cd = cd;
    }

    // ...
}
Notice that this class is annotated as Spring component, and its constructor is autowired. So we expect the framework will look for a suitable component in the CompactDisc hierarchy and wire it to the ctor parameter.

To have the wiring working we need to configure properly the component scan class, so I modify it in this way:
@Configuration
@ComponentScan(basePackageClasses = { CompactDisc.class, MediaPlayer.class })
public class CDPlayerConfig {
}
To test it, I have change the CDPlayerTest to use just a MediaPlayer.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
    @Autowired
    private MediaPlayer player;

    @Test
    public void testPlayerNotNull() {
        assertNotNull(player);
    }

    @Test
    public void testCDInserted() {
        assertTrue(player.hasMedia());
    }

    @Test
    public void testPlay() {
        assertEquals("Sgt. Pepper's Lonely Hearts Club Band by The Beatles", player.play());
    }
}
JUnit, using the Spring class runner, let the framework to do all the required wiring, in the app source code, and also here in the test. I ran it, and I was happy to get full green light.

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.
I have also done a few minor changes to keep the post as slim and readable as possible. For instance I removed the references to the brilliant System Rule library by Stefan Birkner & Marc Philipp.

Full code on github.
Have a look at the soundsystem package and the test file.

No comments:

Post a Comment