单测过程中奇怪的No tests found异常

现象

最近在补单测覆盖率的过程中遇到了一个奇怪的错误, 在添加了PowerMock(版本2.0.9)的@PrepareOnlyThisForTest注解后, 出现了一个奇怪的错误: "No tests found ....". 然而明明加了@Test注解. 代码示例如下:

/**
 * 类的实现描述: 一个静态类
 */
public class ConstantUtil {
    public static int getCount() {
        return 100;
    }
}

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * 类的实现描述: 一个测试类
 */
@RunWith(PowerMockRunner.class)
public class AbcUnitTest {
    @Test
    public void testA() {
        Assert.assertEquals(1, 1);
    }

    @Test
    @PrepareOnlyThisForTest(ConstantUtil.class)
    public void testB() {
        PowerMockito.mockStatic(ConstantUtil.class);
        PowerMockito.when(ConstantUtil.getCount()).thenReturn(50);
        Assert.assertEquals(50, ConstantUtil.getCount());
    }

}

这个错误非常奇怪, 而更奇怪的是我用mvn test运行时确没有这个异常(开始是用IDEA运行的). 网上找了半天也没一个合理的解释. 于是跟踪代码看了一下.

排查

跟踪后发现异常来自类PowerMockJUnit44RunnerDelegateImpl.

    @Override
    public void filter(Filter filter) throws NoTestsRemainException {
        for (Iterator iter = testMethods.iterator(); iter.hasNext(); ) {
            Method method = iter.next();
            if (!filter.shouldRun(methodDescription(method)))
                iter.remove();
        }
        if (testMethods.isEmpty())
            throw new NoTestsRemainException();
    }

PowerMock在运行单测时, 会根据单测类的源代码,本例中就是AbcUnitTest, 生成若干个Delegate. 每一个Delegate中都会有对应的testMethods, 本例中照理说应该是testA,和testA两个方法(为什么说是照理说? 因为这里就是错误的原因). Delegate会把testMethods中的每一个方法跟需要运行的方法对比, 如果不是需要运行的方法, 就从testMethods中移除, 最后如果testMethods中一个方法都没有, 就抛出"No tests found ....". 那现在问题就变成了为什么这个Delegate中没有需要运行的方法(也就是testB)呢?
首先debug代码验证一下抛出异常的Delegate中是否只有方法testA?


图1

符合期望. 猜测@PrepareOnlyThisForTest注解使得PowerMock把原来的代码切割成了两个Delegate, 每个Delegate只包含一个方法. 那这个切割是在哪里做的呢?
最后发现在类AbstractCommonTestSuiteChunkerImpl中有一个方法putMethodToChunk, 这个方法会根据源代码中@Test注解的方法添加到不同的chunk中, 而最终一个chunk会对应一个Delegate. 该方法的代码如下:

private void putMethodToChunk(TestCaseEntry testCaseEntry, Class testClass, Method method) {
        if (shouldExecuteTestForMethod(testClass, method)) {
            currentTestIndex++;
            if (hasChunkAnnotation(method)) {
                LinkedList methodsInThisChunk = new LinkedList();
                methodsInThisChunk.add(method);
                
                final ClassLoader mockClassloader = createClassLoaderForMethod(testClass, method);
                
                final TestChunkImpl chunk = new TestChunkImpl(mockClassloader, methodsInThisChunk);
                testCaseEntry.getTestChunks().add(chunk);
                updatedIndexes();
            } else {
                testCaseEntry.getTestChunks().get(0).getTestMethodsToBeExecutedByThisClassloader().add(method);
                // currentClassloaderMethods.add(method);
                final int currentDelegateIndex = internalSuites.size() - 1;
                /*
                 * Add this test index to the main junit runner
                 * delegator.
                 */
                List testList = testAtDelegateMapper.get(currentDelegateIndex);
                if (testList == null) {
                    testList = new LinkedList();
                    testAtDelegateMapper.put(currentDelegateIndex, testList);
                }
                
                testList.add(currentTestIndex);
            }
        }
    }

可以看到这个方法中有两个分值, 根据条件hasChunkAnnotation(method)来决定是否新建一个chunk, 是就新建, 否则放入已有的chunk. 查看方法hasChunkAnnotation(method), 代码如下;

private boolean hasChunkAnnotation(Method method) {
        return method.isAnnotationPresent(PrepareForTest.class) || method.isAnnotationPresent(SuppressStaticInitializationFor.class)
                       || method.isAnnotationPresent(PrepareOnlyThisForTest.class) || method.isAnnotationPresent(PrepareEverythingForTest.class);
    }

非常简单的函数, 根据注解来决定是否新建chunk, 而其中恰恰包含PrepareForTest注解.
原因找到, 这也可以解释为什么mvn test运行时不会报错, 因为mvn test运行时, 两个方法testA和testB都是需要运行的方法, 两个Delegate中各包含一个需要运行的方法. 而解决方法也相当容易, 把注解加到类上即可(事实上这个方法在stackoverflow上有人提了(https://stackoverflow.com/questions/34956084/junit-test-with-runwithpowermockrunner-class-fails-no-tests-found-matching/40287112#40287112), 因为提问者没有采纳, 所以当时没有放在心上, 而更郁闷的是答案下面有两个评论说"saved my day". 而我被这个错误纠缠了半天, 因为一开始一直觉得是版本问题, 试了各种各样的版本, 不相信PowerMock会有这样的bug(个人认为这应该算是bug).

你可能感兴趣的:(单测过程中奇怪的No tests found异常)