Aspect Not Being Called In Spring Test


Answer :

Not sure what you are trying to do but your @ContextConfiguration is useless as you aren't using Spring Test to run your test (that would require a @RunWith or one of the super classes from Spring Test).

Next you are adding a singleton which is already fully mocked and configured (that is what the context assumes). I strongly suggest to use Spring instead of working around it.

First create a configuration inside your test class for testing, this configuration should do the scanning and register the mocked bean. Second use Spring Test to run your test.

@ContextConfiguration public class SoftwareServiceTests extends AbstractJUnit4SpringContextTests {     private static final Logger LOGGER = LoggerFactory.getLogger(SoftwareServiceTests.class.getName());      @Autowired     private SoftwareService softwareService;      @Test(expected = ValidationException.class)     public void testAddInvalidSoftware() throws ValidationException {         LOGGER.info("Testing add invalid software");         SoftwareObject softwareObject = new SoftwareObject();         softwareObject.setName(null);         softwareObject.setType(null);          this.softwareService.addSoftware(softwareObject);     }      @Configuration     @Import(AspectsConfiguration.class)     public static class TestConfiguration {          @Bean         public SoftwareDAO softwareDao() {             return Mockito.mock(SoftwareDAO.class);         }          @Bean         public MapperFacade domainMapper() {             return Mockito.mock(MapperFacade.class)         }          @Bean         public SoftwareService softwareService() {             SoftwareServiceImpl service = new SoftwareServiceImpl(softwareDao())             return service;         }      } } 

It is good to understand how Spring AOP works. A Spring managed bean gets wrapped in a proxy (or a few) if it is eligible for any aspect (one proxy per aspect).

Typically, Spring uses the interface to create proxies though it can do with regular classes using libraries like cglib. In case of your service that means the implementation instance Spring creates is wrapped in a proxy that handles aspect call for the method validation.

Now your test creates the SoftwareServiceImpl instance manually so it is not a Spring managed bean and hence Spring has no chance to wrap it in a proxy to be able to use the aspect you created.

You should use Spring to manage the bean to make the aspect work.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?