【问题标题】:Mockito error- There were zero interactions with this mock AndroidMockito 错误 - 与此模拟 Android 的交互为零
【发布时间】:2019-12-06 12:46:13
【问题描述】:

我得到通缉但未被调用。 checkFingerPrintWhenTouchIdEnabled() 方法在 verify(fingerPrintHelper, times(1)).initializeFingerPrint(any()); 行与此模拟错误的交互为零 . 甚至我也嘲笑过这个对象,并且在调试 initializeFingerPrint(..) 函数时会被调用。

下面是我要测试的功能,

@RequiresApi(Build.VERSION_CODES.M)
public void checkFingerPrint() {
    if (fingerPrintHelper.isDeviceReadyForFingerPrint()) {
        boolean isFingerPrintEnable = sharedPreference.getBoolean(SpKeys.KEY_FINGER_PRINT, false);
        if (isFingerPrintEnable) {
            fingerPrintHelper.initializeFingerPrint(this);
        }
    } else {
        sharedPreference.putBoolean(SpKeys.KEY_FINGER_PRINT, false).commit();
    }
}

LoginActvity.java

public class LoginActivity extends AppCompatActivity {
public FingerPrintHelper fingerPrintHelper;
ActivityLoginBinding binding;
private LoginViewModel loginViewModel;
private SharedPreferenceManager sharedPreferenceManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    sharedPreferenceManager = new SharedPreferenceManager(getApplicationContext(), SpKeys.MY_SP);
    fingerPrintHelper = new FingerPrintHelper(this);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
    loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
    binding.setViewModel(loginViewModel);
    binding.setLifecycleOwner(this);

    checkFingerPrint();
}


@RequiresApi(Build.VERSION_CODES.M)
public void checkFingerPrint() {
    if (fingerPrintHelper.isDeviceReadyForFingerPrint()) {
        boolean isFingerPrintEnable = sharedPreferenceManager.getBoolean(SpKeys.KEY_FINGER_PRINT, false);
        if (isFingerPrintEnable) {
            fingerPrintHelper.initializeFingerPrint(this);
        }
    } else {
        sharedPreferenceManager.setBoolean(SpKeys.KEY_FINGER_PRINT, false);
    }
}
}

我正在为此函数编写正负测试用例,而 checkFingerPrintWhenTouchIdDisabled() 测试工作正常,但 checkFingerPrintWhenTouchIdEnabled() 测试函数出现错误 请参考下面的测试类

LoginActivityTest.java

public class LoginActivityTest {

LoginActivity loginActivity;
@Mock
FingerPrintHelper fingerPrintHelper;
@Rule
public ActivityTestRule<LoginActivity> loginActivityRule = new ActivityTestRule<>(
        LoginActivity.class);
Context context;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    loginActivity = loginActivityRule.getActivity();
    context = getInstrumentation().getTargetContext();
}

@Test
public void checkFingerPrintWhenTouchIdDisabled() {

    SharedPreferences sharedPreferences = context.getSharedPreferences(SpKeys.MY_SP, Context.MODE_PRIVATE);
    when(fingerPrintHelper.isDeviceReadyForFingerPrint()).thenReturn(false);
    loginActivity.checkFingerPrint();
    Assert.assertFalse(sharedPreferences.getBoolean(SpKeys.KEY_FINGER_PRINT, false));
    verify(fingerPrintHelper, never()).initializeFingerPrint(any());

}
@Test
public void checkFingerPrintWhenTouchIdEnabled() {

    SharedPreferences sharedPreferences = context.getSharedPreferences(SpKeys.MY_SP, Context.MODE_PRIVATE);
    SharedPreferences.Editor preferencesEditor = sharedPreferences.edit();
    when(fingerPrintHelper.isDeviceReadyForFingerPrint()).thenReturn(true);
    preferencesEditor.putBoolean(SpKeys.KEY_FINGER_PRINT, true).commit();

    loginActivity.checkFingerPrint();

    /* Below verification for `initializeFingerPrint()` is throwing error as,
    Actually, there were zero interactions with this mock. error,
    Even I have mock the object & while debugging the method is getting invoked also.
    If I debug my code it calls this function but in test cases it shows above error
    */
    verify(fingerPrintHelper, times(1)).initializeFingerPrint(any());
}
}

那为什么我的测试用例会出现零交互错误?可能是什么问题,感谢任何帮助。

提前致谢。

【问题讨论】:

  • @second 很抱歉给您带来不便。我已经更新了文件。
  • 该异常似乎与您在android environment 中生成某些内容的方式有关。可能与mockito 本身无关,但我也不确定您将如何在单元测试环境中处理这些东西。 -- 设置中的分配不应该是必要的,一个简单的基于规则的带有注释的测试没有它也可以正常工作。
  • 如果我之前理解正确的话,那么最好的选择可能是遵循Maciej Kowalski 的建议并手动设置你的模拟。
  • @second, set up your mocks manually instead. 你能详细说明这个术语吗?如何通过手动设置 mokes 来模拟 LoginActivity?如何使用 setter 注入模拟?我应该为 LoginActivity 这样做吗?
  • 我添加了一个示例作为答案(因为 cmets 中的代码无法正确格式化)。将其视为Maciej Kowalski 答案的扩展。

标签: java android mockito android-testing testcase


【解决方案1】:

尝试以下手动设置模拟(不使用注释):

@Before
public void setUp() {
    loginActivity = loginActivityRule.getActivity();
    loginActivity.fingerPrintHelper = Mockito.mock(FingerPrintHelper.class);
    // ...
}

如果之前可以成功创建loginAcitivy,那么现在应该没有问题了。
而且fingerPrintHelper 似乎是public,所以它很容易设置。
但如果你想正确地做,你可以提供一个setter。


或者如果你想保留创建fingerPrintHelper的注解。

@Mock
FingerPrintHelper fingerPrintHelper;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    loginActivity = loginActivityRule.getActivity();
    loginActivity.fingerPrintHelper = fingerPrintHelper;
    // ...
}

我仍然想知道保留 loginActivity.fingerPrintHelper = fingerPrintHelper 行的原因。

模拟不会神奇地将自身附加到任何其他对象。

@InjectMocks 会为您执行此操作,但 Mockito 似乎无法自行处理您的 LoginActivity 的创建。

所以你唯一能做的就是手动将模拟传递给被测对象。

【讨论】:

  • 它就像一个魅力。谢谢回复。我仍然想知道保留loginActivity.fingerPrintHelper = fingerPrintHelper 行的原因。既然我们已经在做@Mock FingerPrintHelper fingerPrintHelper; 为什么我们需要在setUp() 中添加loginActivity.fingerPrintHelper = fingerPrintHelper 行@
  • 添加了一个简短的解释,希望它更清楚。
  • 嗨@second,请也检查这个问题stackoverflow.com/q/58367198/6532155
【解决方案2】:

您没有在测试用例的任何地方注入模拟。我假设在构造函数/工厂中创建了一个普通实例。

要么使用 SUT 的设置器,要么让 Mockito 为你注入它:

@InjectMocks
LoginActivity loginActivity;

仅使用@Mock 是不够的。

【讨论】:

  • @MaciejKowaski 感谢您的回复,使用@InjectMocks 后我遇到了错误,org.mockito.exceptions.misusing.InjectMocksException: Cannot instantiate @InjectMocks field named 'loginActivity' of type 'class com.mytest.LoginActivity'. You haven't provided the instance at field declaration so I tried to construct the instance. However the constructor or the initialization block threw an exception : Can't create handler inside thread that has not called Looper.prepare()
  • 该类很可能没有公共的无参数构造函数。您需要使用 setter 注入模拟然后
  • 嗨@Maciej Kowalski 如何在以下情况下处理MockWebServer stackoverflow.com/q/58367198/6532155 ?请检查这个问题。
猜你喜欢
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
相关资源
最近更新 更多