|
| 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.CoreMatchers.notNullValue; |
| 21 | +import static org.hamcrest.Matchers.hasSize; |
| 22 | +import static org.junit.Assert.assertThat; |
| 23 | +import static org.junit.Assert.assertTrue; |
| 24 | + |
| 25 | +@RunWith(SpringJUnit4ClassRunner.class) |
| 26 | +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) |
| 27 | +public class AopPerformanceTest { |
| 28 | + |
| 29 | + @Before |
| 30 | + public void setUp() { |
| 31 | + logEventHandler = new Handler() { |
| 32 | + @Override |
| 33 | + public void publish(LogRecord record) { |
| 34 | + messages.add(record.getMessage()); |
| 35 | + } |
| 36 | + |
| 37 | + @Override |
| 38 | + public void flush() { |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public void close() throws SecurityException { |
| 43 | + } |
| 44 | + }; |
| 45 | + |
| 46 | + messages = new ArrayList<>(); |
| 47 | + } |
| 48 | + |
| 49 | + @Autowired |
| 50 | + private FooDao dao; |
| 51 | + |
| 52 | + private Handler logEventHandler; |
| 53 | + |
| 54 | + private List<String> messages; |
| 55 | + |
| 56 | + @Test |
| 57 | + public void givenPerformanceAspect_whenCallDaoMethod_thenPerformanceMeasurementAdviceIsCalled() { |
| 58 | + Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); |
| 59 | + logger.addHandler(logEventHandler); |
| 60 | + |
| 61 | + final String entity = dao.findById(1L); |
| 62 | + assertThat(entity, notNullValue()); |
| 63 | + assertThat(messages, hasSize(1)); |
| 64 | + |
| 65 | + String logMessage = messages.get(0); |
| 66 | + Pattern pattern = Pattern.compile("Execution of findById took \\d+ ms"); |
| 67 | + assertTrue(pattern.matcher(logMessage).matches()); |
| 68 | + } |
| 69 | +} |
0 commit comments