简体   繁体   English

如何为JUnit测试声明“mixins”?

[英]How can I declare “mixins” for JUnit tests?

I have a lot of JUnit tests in my projects. 我的项目中有很多JUnit测试。 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... 我以为我可以使用一些mixins进行测试,我可以像这样用...

@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. 我的意思是,检查连接是否已关闭很简单,但在每个测试类或方法中手动将代码放到@Before@After方法似乎是个坏主意。

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 你可以在junit测试中使用@AfterClass@After注释,并在那里实现checkConnection

http://junit.sourceforge.net/javadoc/org/junit/After.html http://junit.sourceforge.net/javadoc/org/junit/AfterClass.html 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. 您正在寻找的东西似乎被称为Aspects。 Using Aspect you can define an interceptor that runs in particular case. 使用Aspect可以定义在特定情况下运行的拦截器。

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 看看这个链接 - 它是关于如何让JUnit在每个测试方法调用之前使用方面执行: AspectJ + Junit + Maven - 在测试中识别出切入点但是抛出NoSuchMethodError:aspectOf()异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM