執行@Rule
/@Before
/@Test
JUnit中的註釋序列取決於Runner實現。比方說,SpringJUnit4ClassRunner.methodBlock
或BlockJUnit4ClassRunner.methodBlock
的樣子:在此基礎上
Statement statement = methodInvoker(frameworkMethod, testInstance);
statement = possiblyExpectingExceptions(frameworkMethod, testInstance, statement);
statement = withBefores(frameworkMethod, testInstance, statement);
...
statement = withRules...
我可以提出與壓倒一切的methodInvoker
下面的實現和增加新的@RightBeforeTest
註釋
package info.test;
import org.junit.Before;
import org.junit.Test;
import org.junit.internal.runners.statements.RunBefores;
import org.junit.runner.RunWith;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static org.junit.Assert.assertEquals;
@RunWith(JUnit4AnnotationsSequenceTest.CustomSpringJUnit4ClassRunner.class)
public class JUnit4AnnotationsSequenceTest
{
private String value = null;
@Before
public void setUp()
{
value = "@Before.setUp";
}
@RightBeforeTest
public void latestChance()
{
value = "@RightBeforeTest.latestChance";
}
@Test
public void rightBeforeTestAnnotationExecutesAfterBeforeAnnotation()
{
assertEquals("@RightBeforeTest.latestChance", value);
}
public static class CustomSpringJUnit4ClassRunner extends SpringJUnit4ClassRunner
{
public CustomSpringJUnit4ClassRunner(final Class<?> clazz) throws InitializationError
{
super(clazz);
}
protected Statement methodInvoker(final FrameworkMethod method, final Object test)
{
return new RunBefores(
super.methodInvoker(method, test),
getTestClass().getAnnotatedMethods(RightBeforeTest.class),
test);
}
}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface RightBeforeTest {}
}
![test result](https://i.stack.imgur.com/W3mzs.png)
你能添加清除代碼在設置SQL執行後,@Before方法中的SQL計數器? –
它在ttddyy/datasource-proxy(https://github.com/ttddyy/datasource-proxy)的幫助下實現,就像本文一樣 - https://vladmihalcea.com/2014/02/01/how-to-detect -n-plus-one-query-problem-testing-testing(QueryCountHolder.clear();) – Alex