單測(cè)過(guò)程中奇怪的No tests found異常

現(xiàn)象

最近在補(bǔ)單測(cè)覆蓋率的過(guò)程中遇到了一個(gè)奇怪的錯(cuò)誤, 在添加了PowerMock(版本2.0.9)的@PrepareOnlyThisForTest注解后, 出現(xiàn)了一個(gè)奇怪的錯(cuò)誤: "No tests found ....". 然而明明加了@Test注解. 代碼示例如下:

/**
 * 類的實(shí)現(xiàn)描述: 一個(gè)靜態(tài)類
 */
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;

/**
 * 類的實(shí)現(xiàn)描述: 一個(gè)測(cè)試類
 */
@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());
    }

}

這個(gè)錯(cuò)誤非常奇怪, 而更奇怪的是我用mvn test運(yùn)行時(shí)確沒(méi)有這個(gè)異常(開(kāi)始是用IDEA運(yùn)行的). 網(wǎng)上找了半天也沒(méi)一個(gè)合理的解釋. 于是跟蹤代碼看了一下.

排查

跟蹤后發(fā)現(xiàn)異常來(lái)自類PowerMockJUnit44RunnerDelegateImpl.

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

PowerMock在運(yùn)行單測(cè)時(shí), 會(huì)根據(jù)單測(cè)類的源代碼,本例中就是AbcUnitTest, 生成若干個(gè)Delegate. 每一個(gè)Delegate中都會(huì)有對(duì)應(yīng)的testMethods, 本例中照理說(shuō)應(yīng)該是testA,和testA兩個(gè)方法(為什么說(shuō)是照理說(shuō)? 因?yàn)檫@里就是錯(cuò)誤的原因). Delegate會(huì)把testMethods中的每一個(gè)方法跟需要運(yùn)行的方法對(duì)比, 如果不是需要運(yùn)行的方法, 就從testMethods中移除, 最后如果testMethods中一個(gè)方法都沒(méi)有, 就拋出"No tests found ....". 那現(xiàn)在問(wèn)題就變成了為什么這個(gè)Delegate中沒(méi)有需要運(yùn)行的方法(也就是testB)呢?
首先debug代碼驗(yàn)證一下拋出異常的Delegate中是否只有方法testA?


圖1

符合期望. 猜測(cè)@PrepareOnlyThisForTest注解使得PowerMock把原來(lái)的代碼切割成了兩個(gè)Delegate, 每個(gè)Delegate只包含一個(gè)方法. 那這個(gè)切割是在哪里做的呢?
最后發(fā)現(xiàn)在類AbstractCommonTestSuiteChunkerImpl中有一個(gè)方法putMethodToChunk, 這個(gè)方法會(huì)根據(jù)源代碼中@Test注解的方法添加到不同的chunk中, 而最終一個(gè)chunk會(huì)對(duì)應(yīng)一個(gè)Delegate. 該方法的代碼如下:

private void putMethodToChunk(TestCaseEntry testCaseEntry, Class<?> testClass, Method method) {
        if (shouldExecuteTestForMethod(testClass, method)) {
            currentTestIndex++;
            if (hasChunkAnnotation(method)) {
                LinkedList<Method> methodsInThisChunk = new LinkedList<Method>();
                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<Integer> testList = testAtDelegateMapper.get(currentDelegateIndex);
                if (testList == null) {
                    testList = new LinkedList<Integer>();
                    testAtDelegateMapper.put(currentDelegateIndex, testList);
                }
                
                testList.add(currentTestIndex);
            }
        }
    }

可以看到這個(gè)方法中有兩個(gè)分值, 根據(jù)條件hasChunkAnnotation(method)來(lái)決定是否新建一個(gè)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);
    }

非常簡(jiǎn)單的函數(shù), 根據(jù)注解來(lái)決定是否新建chunk, 而其中恰恰包含PrepareForTest注解.
原因找到, 這也可以解釋為什么mvn test運(yùn)行時(shí)不會(huì)報(bào)錯(cuò), 因?yàn)閙vn test運(yùn)行時(shí), 兩個(gè)方法testA和testB都是需要運(yùn)行的方法, 兩個(gè)Delegate中各包含一個(gè)需要運(yùn)行的方法. 而解決方法也相當(dāng)容易, 把注解加到類上即可(事實(shí)上這個(gè)方法在stackoverflow上有人提了(https://stackoverflow.com/questions/34956084/junit-test-with-runwithpowermockrunner-class-fails-no-tests-found-matching/40287112#40287112), 因?yàn)樘釂?wèn)者沒(méi)有采納, 所以當(dāng)時(shí)沒(méi)有放在心上, 而更郁悶的是答案下面有兩個(gè)評(píng)論說(shuō)"saved my day". 而我被這個(gè)錯(cuò)誤糾纏了半天, 因?yàn)橐婚_(kāi)始一直覺(jué)得是版本問(wèn)題, 試了各種各樣的版本, 不相信PowerMock會(huì)有這樣的bug(個(gè)人認(rèn)為這應(yīng)該算是bug).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容