BAEL-4844: Code for the AspectJ class annotation article.

This commit is contained in:
bhandy
2021-03-23 21:52:58 -04:00
parent e0b4e6bcd6
commit cfee931194
8 changed files with 177 additions and 0 deletions
@@ -0,0 +1,30 @@
package com.baeldung.aspectj.classmethodadvice;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
public class MyTracedServiceConsumerUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Spy
private MyTracedService myTracedService;
@Test
public void whenCallingConsumer_thenServiceIsCalled() {
doNothing().when(myTracedService).performSomeLogic();
doNothing().when(myTracedService).performSomeAdditionalLogic();
new MyTracedServiceConsumer(myTracedService);
verify(myTracedService).performSomeLogic();
verify(myTracedService).performSomeAdditionalLogic();
}
}
@@ -0,0 +1,40 @@
package com.baeldung.aspectj.classmethodadvice;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.test.system.OutputCaptureRule;
import static org.junit.Assert.assertTrue;
/*
* When running this test class, the tests may fail unless you build the code with Maven first. You
* must ensure the AspectJ compiler executes to weave in the Aspect's logic. Without the Aspect
* weaved into the class under test, the trace logging will not be written to stdout.
*/
public class MyTracedServiceUnitTest {
@Rule
public OutputCaptureRule outputCaptureRule = new OutputCaptureRule();
@Test
public void whenPerformingSomeLogic_thenTraceAndInfoOutputIsWritten() {
MyTracedService myTracedService = new MyTracedService();
myTracedService.performSomeLogic();
String output = outputCaptureRule.getOut();
assertTrue(output.contains("TracingAspect - Entering MyTracedService.performSomeLogic"));
assertTrue(output.contains("MyTracedService - Inside performSomeLogic"));
assertTrue(output.contains("TracingAspect - Exiting MyTracedService.performSomeLogic"));
}
@Test
public void whenPerformingSomeAdditionalLogic_thenTraceAndInfoOutputIsWritten() {
MyTracedService myTracedService = new MyTracedService();
myTracedService.performSomeAdditionalLogic();
String output = outputCaptureRule.getOut();
assertTrue(output.contains("TracingAspect - Entering MyTracedService.performSomeAdditionalLogic"));
assertTrue(output.contains("MyTracedService - Inside performSomeAdditionalLogic"));
assertTrue(output.contains("TracingAspect - Exiting MyTracedService.performSomeAdditionalLogic"));
}
}