I have a lot of JUnit tests in my projects. Some of them have some side-effects that can influence the execution of other tests. For example, they open database connections and forget to close them, and then at some point tests start to fail because they reached the limit. I thought that I could use some mixins for the test, that I could use like this...
@CheckThatConnectionsAreClosed
@LogExecutionTime
@Test
public void testSomething() {
// ...
sessionFactory.openSession(); // hey look! I didn't close it!
// ...
}
...so that when I run it, I'd get an assertion error plus information about the execution time.
I mean, checking that connections are closed is simple, but putting code manually to @Before
and @After
method in each test class or method seems like a bad idea.
Those annotations I think of would be effectively method interceptors and I guess that it would be possible with a custom test runner. But maybe there is some simpler way to achieve this? Or maybe it's already done in some good library?
It sounds as though a custom Rule would be the way to go. Rules are intended as bits of reusable setup/tear-down functionality, to avoid having to use Before/After or custom Runners.
You could use @AfterClass
or @After
annotation in that junit tests and implement checkConnection there
http://junit.sourceforge.net/javadoc/org/junit/After.html http://junit.sourceforge.net/javadoc/org/junit/AfterClass.html
It seems that what you're looking for is called Aspects. Using Aspect you can define an interceptor that runs in particular case.
Check out this link - it' about how to get JUnit working with aspects executed before each test method call: AspectJ + Junit + Maven - pointcut recognized in tests but NoSuchMethodError: aspectOf() exception thrown
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.