android - 未完成的 stub 异常

标签 android testing mockito

我是 android 单元测试的新手。 我的问题是我有一个帮助程序类用于从 dp 获取像素。 这段代码运行良好并且有一个静态方法。 当我想为这个类写一个测试时,我给出了这个错误:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.sooran.emdad.ExampleUnitTest.setup(ExampleUnitTest.java:70)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn' 
instruction is completed


at com.sooran.emdad.Util.DpUtil2.toPixels(DpUtil2.java:10)
at com.sooran.emdad.ExampleUnitTest.setup(ExampleUnitTest.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at 

sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:74)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:53)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

这是我的课:

public class DpUtil2 {

public static int toPixels(int dp, Context context) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    float value=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
    return (int) value;

}

这是我的测试代码:

@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {

@Mock
Context context;
@Mock
Resources resources;
@Mock
DisplayMetrics displayMetrics=new DisplayMetrics();
@Mock
DpUtil2 dpUtil;

@Test
public void addition_isCorrect() {
    assertEquals(4, 2 + 2);
}

@Test
public void dpTest(){

    assertEquals(dpUtil.toPixels(64,context),168);

}

@Before
public void setup(){

    displayMetrics.setToDefaults();
    displayMetrics.density=2.625f;
    displayMetrics.widthPixels=1080;
    displayMetrics.heightPixels=1794;
    displayMetrics.scaledDensity=2.625f;
    displayMetrics.xdpi=422.03f;
    displayMetrics.ydpi=424.069f;
    displayMetrics.densityDpi=420;

    int x=168;
    doReturn(resources).when(context).getResources();
    doReturn(displayMetrics).when(resources).getDisplayMetrics();

    doReturn(x).when(dpUtil).toPixels(64,context);
    }

我可以通过 remove third do return 正确地通过测试 但是为什么第三个返回会给出这个错误

最佳答案

那么,为了测试静态方法,您需要使用 PowerMock,我使用了您的示例并进行了修改。

   package com.sample.mass;

    import android.content.Context;
    import android.content.res.Resources;
    import android.util.DisplayMetrics;

    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.mockito.MockitoAnnotations;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({DpUtil2.class})
public class DpUtil2Test {


    private DpUtil2 mDpUtil2;

    @Mock
    Context mContext;

    @Mock
    Resources mResources;

    @Mock
    DisplayMetrics mDisplayMetrics;


    private int dp = 20;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        Mockito.when(mResources.getDisplayMetrics()).thenReturn(mDisplayMetrics);
        Mockito.when(mContext.getResources()).thenReturn(mResources);

    }

    @Test
    public void testToPixels() throws Exception {
        System.out.println("yes");
        PowerMockito.mockStatic(DpUtil2.class);
        PowerMockito.when(DpUtil2.toPixels(dp, mContext)).thenReturn(dp);

        int actualResult = DpUtil2.toPixels(dp, mContext);
        //expected, actual
        Assert.assertEquals(dp, actualResult);

        PowerMockito.verifyStatic(DpUtil2.class);
        DpUtil2.toPixels(dp, mContext);
        System.out.println("-----------we are done--------------------");
    }
}

并在 gradle 中使用它们,

 testImplementation 'org.mockito:mockito-core:2.2.0'
    testImplementation 'org.powermock:powermock-core:1.7.1'
    testImplementation 'org.powermock:powermock-module-junit4:1.7.1'
    testImplementation 'org.powermock:powermock-api-mockito2:1.7.1'

关于android - 未完成的 stub 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313523/

相关文章:

GWT 和 MVP 模式中的 Mock View

android - Google Play 服务的 Firebase 分析已过时

ruby-on-rails - 在编写不相关的测试时,Rails 密码验证错误地失败

java - 获取 java.lang.ClassNotFoundException : org. testng.TestNG 错误

ruby-on-rails - 在使用 Webrat 进行测试时如何捕获到其他域的重定向?

scala - 使用 Mockito 对 LazyLogging 进行单元测试

java - 使用 Mockito 进行单元测试时出现空指针

java - Android 尝试运行 unix 可执行文件 : syntax error: '__TEXT' unexpected

android - 在 Android 应用中使用 Material Design 2

android - 确定用户在 osm map 上的位置