如何为在单元测试期间的流程中调用的静态方法返回不同的值?

问题描述 投票:1回答:1

我正在尝试为以下代码段编写单元测试。

class ABC {
    int getMyValue(final Activity activity) {
        if(MyClass.getInstance(activity).getValue() == 1) return 10;
        else return 20;
    }

    void doSomething() {
    }
}

我已经尝试过类似的方法来测试doSomething功能。

mABC = new ABC();

public void test_doSomething() {
   doReturn(20).when(mABC).getMyValue();
   //validate
}

我如何类似地测试getMyValue?我想断言当值为1时返回10,而在所有其他情况下,返回20。

我正在我的android应用程序中执行此操作。有没有现有的框架可以帮助我做到这一点?

编辑:

MyClass看起来像这样

public class MyClass {

   private static Context mContext;
   public static getInstance(Context context) {
     mContext = context;
     return new MyClass();
   }

   private MyClass() {}

   public void getDreamValue() {
     Settings.Secure.getInt(mContext.getContentResolver(), "dream_val", -1);
   }
}
android unit-testing junit mockito robolectric
1个回答
1
投票

您可以考虑如下修改MyClass

public class MyClass {

   private static Context mContext;

   // Create a private variable that holds the instance. 
   private Myclass instance;

   public static getInstance(Context context) {
     mContext = context;

     if (instance == null) 
         instance = new MyClass(); // Assign the instance here 

     return instance;
   }

   private MyClass() {}

   public void getDreamValue() {
     Settings.Secure.getInt(mContext.getContentResolver(), "dream_val", -1);
   }
}

现在,当您使用Robolectric时,可以在测试类中将instance值设置为模拟值,如下所示。

@RunWith(RobolectricTestRunner.class) 
public class ABCTest {

    @Mock
    MyClass mockInstance; 

    @Mock
    Context mockContext; 

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        // Set the mock instance for MyClass
        ReflectionHelpers.setStaticField(MyClass.class, "instance", mockInstance);
    }

    @Test
    public void testWhen1() {
       doReturn(1).when(mockInstance).getDreamValue();
       Assert.assertEquals(10, new ABC().getMyValue());
    }

    @Test
    public void testWhenNot1() {
       doReturn(2).when(mockInstance).getDreamValue();
       Assert.assertEquals(20, new ABC().getMyValue());
    }

    @After
    public void tearDown() {
        // Set the instance to null again to enable further tests to run 
        ReflectionHelpers.setStaticField(MyClass.class, "instance", null);
    }
}

我希望有帮助。

注意:您似乎想提供MyClass的单例实例。因此,您实际上不应该在MyClass函数中创建getInstance的新实例。我避免每次使用代码中的null检查来创建新实例。

© www.soinside.com 2019 - 2024. All rights reserved.