|
| 1 | +package org.baeldung.aop; |
| 2 | + |
| 3 | +import org.baeldung.config.TestConfig; |
| 4 | +import org.baeldung.dao.FooDao; |
| 5 | +import org.junit.Before; |
| 6 | +import org.junit.Test; |
| 7 | +import org.junit.runner.RunWith; |
| 8 | +import org.springframework.beans.factory.annotation.Autowired; |
| 9 | +import org.springframework.test.context.ContextConfiguration; |
| 10 | +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; |
| 11 | +import org.springframework.test.context.support.AnnotationConfigContextLoader; |
| 12 | + |
| 13 | +import java.util.ArrayList; |
| 14 | +import java.util.List; |
| 15 | +import java.util.logging.Handler; |
| 16 | +import java.util.logging.LogRecord; |
| 17 | +import java.util.logging.Logger; |
| 18 | +import java.util.regex.Pattern; |
| 19 | + |
| 20 | +import static org.hamcrest.Matchers.hasSize; |
| 21 | +import static org.junit.Assert.assertThat; |
| 22 | +import static org.junit.Assert.assertTrue; |
| 23 | + |
| 24 | +@RunWith(SpringJUnit4ClassRunner.class) |
| 25 | +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) |
| 26 | +public class AopLoggingTest { |
| 27 | + |
| 28 | + @Before |
| 29 | + public void setUp() { |
| 30 | + logEventHandler = new Handler() { |
| 31 | + @Override |
| 32 | + public void publish(LogRecord record) { |
| 33 | + messages.add(record.getMessage()); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public void flush() { |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public void close() throws SecurityException { |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + messages = new ArrayList<>(); |
| 46 | + } |
| 47 | + |
| 48 | + @Autowired |
| 49 | + private FooDao dao; |
| 50 | + |
| 51 | + private Handler logEventHandler; |
| 52 | + |
| 53 | + private List<String> messages; |
| 54 | + |
| 55 | + @Test |
| 56 | + public void givenLoggingAspect_whenCallDaoMethod_thenBeforeAdviceIsCalled() { |
| 57 | + Logger logger = Logger.getLogger(LoggingAspect.class.getName()); |
| 58 | + logger.addHandler(logEventHandler); |
| 59 | + |
| 60 | + dao.findById(1L); |
| 61 | + assertThat(messages, hasSize(1)); |
| 62 | + |
| 63 | + String logMessage = messages.get(0); |
| 64 | + Pattern pattern = Pattern.compile("^\\[\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}\\]findById$"); |
| 65 | + assertTrue(pattern.matcher(logMessage).matches()); |
| 66 | + } |
| 67 | +} |
0 commit comments