【发布时间】:2020-10-01 07:26:22
【问题描述】:
我想使用 mockito 检查某些方法的调用顺序。我要检查的方法之一是在模拟中,另一种是在我正在测试的真实类中,所以我使用 spy 对象来检查:
但是,mockito 只知道对 mock 方法的调用,而不是对 spy 对象的调用:
MigrationServiceImpl migrationServiceSpy = spy(migrationServiceImpl);
// I have tested without no more configuraitons on the spy, and also with the following
// by separate (one by one)
// I tried this:
doNothing().when(migrationServiceSpy).updateCheckpointDate(eq(migration), any(Instant.class)); // In this case the call is not tracked by InOrder
// And this:
when(migrationServiceSpy.updateCheckpointDate(eq(migration), any(Instant.class))).thenReturn(true); // In this case the call is not tracked by InOrder
// And this:
when(migrationServiceSpy.updateCheckpointDate(eq(migration), any(Instant.class))).thenCallRealMethod(); // This line is throwing a null pointer exception but I don't understand why, since if I do not spy the real object it works without failing.
//Here I call the real method
migrationServiceImpl.updateStatus(DEFAULT_MIGRATION_ID, inProgressStatus);
InOrder inOrder = inOrder(migrationServiceSpy, mongoMigrationRunner);
inOrder.verify(migrationServiceSpy).updateCheckpointDate(any(Migration.class), any(Instant.class));
inOrder.verify(mongoMigrationRunner).runMigrationForInterval(any(Migration.class), anyString(), any(Instant[].class));
我能做什么?发生了什么?
【问题讨论】:
-
如果你不模拟 spy 对象,它将调用对象的真实方法。所以你可以在模拟之前检查真实的方法。
-
我也尝试不模拟间谍对象上的任何方法,但在这种情况下,间谍不知道该方法被调用。而且我不能使用原始对象代替间谍,因为 InOrder 只接受模拟或间谍......
-
也试过你说的(调用de funcionality测试然后创建spy,不行)