我有一个我想测试的方法:
Public String doSomething (MyActivity activity , int number) {
// do some stuff/math calculations
float aX = number / 3450;
float bX = aX / 2;
float cX = bX * 6;
return activity.getString(R.string.NameOfProduct, cX)
}
我作为一个测试用例考虑的是检查计算,所以我测试它的下一个方法:
@Test
public void validDoSomething() throws Exception {
myObject = Mockito.spy(MyActivity.class);
ArgumentCaptor<Integer> captor=ArgumentCaptor.forClass(Integer.class);
MyActivity activity = Mockito.mock(MyActivity.class);
when(activity.getString(anyInt(),captor.capture())).thenReturn(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) {
return (String) invocation.getArguments()[0];
}
}.toString());
int x = 9;
String test = myObject.validDoSomething (activity, x)
float aX = x / 3450;
float bX = aX / 2;
float cX = bX * 6;
assertEquals(test ,cX)
}
因为activity.getString()
关闭并使用Android上下文等等所以我想到只返回计算出的参数,我将验证我的(相同)计算。所以我有点超越它。
事情是响应我得到一个名为Test / Class的对象......而不是我传递的实际参数
答案 0 :(得分:3)
The reason why you are having so much trouble to test a simple function is because you have mixed your business logic and UI logic at the same place. I would suggest that you move out the logic that is doing the calculation to a separate function and use the return value of the function in your activity. That way your business logic will be independent of the UI logic and easily testable.
public float doSomething ( int number) {
float aX = number / 3450;
float bX = aX / 2;
float cX = bX * 6;
return cx;
}
In your activity: activity.getString(R.string.NameOfProduct, doSomething(number))