1

The problem is that I am not able to mock this aspectj class while running the unit test because somehow it is injected in context before I mock it.

Example Code -

@Aspect  
public class ExampleAspect {

@Around ("execution * com.*.*.*(..)") 
public void printResult(ProceedingJoinPoint joinPoint) throws Throwable {
       System.out.println("Before Method Execution");
       joinPoint.proceed();
      System.out.println("After Method Execution");
     }    }

Test class -

public class ClassATest 
{
    @Mock
    private ExampleAspect mockExampleAspect;

    private ClassA testClass;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        Mockito.doNothing().when(mockExampleAspect).printResult(anyList());
        testClass = new ClassA();
    }

    @Test
    public void test() {
      // before and after methodA() is executed it is intercepted by the bean of ExampleAspect
      testClass.methodA();
    }
}

I am able to use this aspect successfully. The problem is with the unit test case. How can i mock this aspectj class or disable aspectj for unit testcase? Thanks

akku
  • 11
  • 1
  • 2

1 Answers1

0

You don't need a mock as you can take advantage of Spring framework's AspectJProxyFactory class to test your aspect. Here is a simple example,

public class ClassATest {

    private ClassA proxy;

    @Before
    public void setup() {
        ClassA target = new ClassA();
        AspectJProxyFactory factory = new AspectJProxyFactory(target);
        ExampleAspect aspect = new ExampleAspect();
        factory.addAspect(aspect);
        proxy = factory.getProxy();
    }

    @Test
    public void test() {
        proxy.methodA();
    }
}
Indra Basak
  • 7,124
  • 1
  • 26
  • 45
  • Thanks but i get below error now -Advice must be declared inside an aspect type: Offending method – akku Nov 10 '17 at 07:50
  • Your pointcut has an error. Try this `@Around("execution(* com.*.*.*(..))")`. – Indra Basak Nov 10 '17 at 07:59
  • The pointcut given in the example has a typo. I am able to run using the pointcut but the unit case are failing. Came across one post for the above error - https://stackoverflow.com/questions/31329009/unit-test-a-method-that-is-advised-by-around-advice . I was using MockitoJUnitRunner and now changing the unit case to use SpringJUnit4ClassRunner and create bean in my test config but the bean is not created. I am new to this and trying it further. – akku Nov 10 '17 at 09:28