Powermockito NotAMockException, хотя объект является имитацией - PullRequest
0 голосов
/ 13 февраля 2020

Я пытаюсь смоделировать Uri.parse (), чтобы всегда возвращать поддельный объект Uri. К сожалению, мне сказали, что объект, который я пытаюсь вернуть, не является поддельным объектом, но я не могу понять, почему.

Мой код:

package com.example.recyclerview;

import android.net.Uri;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Uri.class})
public class SimpleExampleTest {

    @Test
    public void setup(){
        PowerMockito.mockStatic(Uri.class);
        Uri uri = mock(Uri.class);
        try {
            // this line causes the error
            PowerMockito.when(Uri.class, "parse", anyString()).thenReturn(uri);
            // also tried line below, but still got the same error:
            // PowerMockito.doReturn(uri).when(Uri.class, "parse", anyString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Мой build.gradle:

// Unit Tests
    //jUnit
    testImplementation 'junit:junit:4.12'
    //Mockito
    testImplementation 'org.mockito:mockito-core:2.8.9'
    // Mockito mock okHttp Response (and probably other final classes)
    testImplementation 'org.mockito:mockito-inline:2.13.0'
    // Json for mockito
    testImplementation 'org.json:json:20140107'
    // Instant executor rule
    testImplementation "androidx.arch.core:core-testing:2.1.0"
    // PowerMockito to extend Mockito for static methods
    testImplementation "org.powermock:powermock-api-mockito2:2.0.5"
    testImplementation "org.powermock:powermock-module-junit4:2.0.5"

Это ошибка, которую я получаю:

org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class

1 Ответ

0 голосов
/ 17 февраля 2020

Ошибка, похоже, связана с проблемами Mockito / Powermockito. Чтобы решить эту проблему, мне пришлось использовать следующие версии Mockito:

testImplementation 'org.mockito:mockito-core:2.23.4'

testImplementation "org.powermock:powermock-api-mockito2:2.0.0"
testImplementation "org.powermock:powermock-module-junit4:2.0.0"

См. Также обсуждение здесь: https://github.com/powermock/powermock/issues/992#issuecomment -537439824

...