O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.4. Applying Mock Components to Support Unit Testing

Problem

You want to unit test your own component in isolation by providing a test harness implementation of a component that your component uses.

Solution

Create a mock implementation of the external component that your component depends on. Create an aspect that applies the mock component implementation in place of the real component.

When unit testing is complete, use a separate AspectJ build configuration file to switch out the testing aspect so the real implementation can be used again.

Discussion

When you are creating your software components, unit test those components in isolation to ensure that the component works as it should. However, when your component relies on other components, it can be tricky and error prone to manually unhook all of the dependencies to the external components for the unit testing and to restore those hooks when unit testing is complete.

Example 20-9 shows a typical situation where MyComponent is the component to be tested, and it has dependencies on an external implementation of ThirdPartyComponentInterface . The real implementation of ThirdPartyComponentInterface is retrieved by making a call to the factory method ThirdPartyFactory.getThirdPartyComponent().

Example 20-9. Creating and using an external component

package com.ourcompany; import com.thirdparty.ThirdPartyComponentFactory; import com.thirdparty.ThirdPartyComponentInterface; public class MyComponent implements MyComponentInterface { private ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required