Summary of Android unit testing issues (Robolectric+JUnit)

Summary of code unit testing issues:

1. The test class refers to the third-party jar package class and reports an error

Cause of the problem:
The tested library does not contain the third-party jar package.

Solution:
add third-party jar package configuration to gradle under app: testImplementation files('libs/third.jar')

2. The custom Shadow class does not take effect, and it still prompts that the shadow class cannot be found

Cause of the problem:
Check whether PowerMock is used, and Shadow does not take effect after using PowerMock for self-test

Solution: Try
to remove PowerMock and use Mockito instead, or replace all third-party dependencies with Shadow. I have no good way.

3. Test the singleton class. Sometimes a single test case can be run, but it fails when running the unit test of the entire class.

Cause of the problem:
The singleton object is obtained in the setUp method, but there is no blank in the tearDown, and one singleton object is obtained each time, so the value set in the previous test still takes effect.

Solution:
Add a destroy method to the singleton class, empty the singleton object sInstance, execute the setUp method before each test case starts to obtain a new object, and execute the destroy method in tearDown.

4. When using PowerMock, an error is reported: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)ClassNotFoundException

Reasons for the problem:
(1) The first reason is that the version number correspondence between Mockito and PowerMock is incorrect. Correspondence can refer to the following blog:

PowerMock,遇到java.lang.ClassNotFoundException: org.mockito.cglib.proxy.MethodInterceptor

(2) Without @PowerMockIgnore({ "org.mockito. ", "org.robolectric. ", "android.*" })

5. When using PowerMock, a null pointer is reported. For example, the method funcD in B is called in the ATest class, and the context is used in this method to report an error, and the Context is empty.

Solution: PowerMockito.doNothing().when(B object).funcD();

6. When testing the configuration testCoverageEnabled, do not configure it in the release configuration to affect the running speed, but configure it in the debug configuration.

buildTypes {
    
    
        debug{
    
    
            testCoverageEnabled true
        }
        release {
    
    
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

Guess you like

Origin blog.csdn.net/kongqwesd12/article/details/129439156