Android 如何为单元测试期间在流中调用的静态方法返回不同的值?
我正试图为下面的代码片段编写单元测试Android 如何为单元测试期间在流中调用的静态方法返回不同的值?,android,unit-testing,junit,mockito,robolectric,Android,Unit Testing,Junit,Mockito,Robolectric,我正试图为下面的代码片段编写单元测试 class ABC { int getMyValue(final Activity activity) { if(MyClass.getInstance(activity).getValue() == 1) return 10; else return 20; } void doSomething() { } } 我尝试过类似的方法来测试doSomething函数 mABC = new AB
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);
}
}
您可以考虑修改<代码> 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时,您可以在测试类中将实例
值设置为mock,如下所示
@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
的单例实例。因此,您确实不应该在getInstance
函数中创建MyClass
的新实例。我避免每次都创建一个新实例,在我的代码中使用null
检查 你能分享一下MyClass
的要点吗?哦,当然这只是一个与Settings.secure
交互的安全设置帮助类,它使用它的getInt
api并将值返回给其他类。你确定你需要静态访问器吗,这对我来说似乎是一个容易出错的解决方案?而且我认为这甚至不会编译,因为mContext不是静态的。构造函数公共MyClass(上下文)
就足够了吗?这将使私有化默认构造函数也变得不必要。你是对的!我的错。我说的是singleton,但每次都创建新实例,这与之相反。谢谢你纠正它。