从Jmockit切换到Mockito



所以我决定从Jmockit搬到Mockito,对我来说似乎很奇怪,我不明白某些事情在Mockito中的工作方式

我有一种简单的@beforeach方法,当我的对象被模拟时,我总是会得到一个无效的指针异常

@Mock
public EntityManager entityManager;
@Mock
public TimerSessionBean timerSessionBean;
@Mock
public Client client;
private CaseSetReminder caseSetReminder;
private Request request;
private Message message;
@BeforeEach
final void beforeEach() {
    request = new Request();
    message = new Message();
    String spaceId = "SPACE_ID";
    String threadId = "THREAD_ID";
    caseSetReminder = new CaseSetReminder();
    caseSetReminder.entityManager = entityManager;
    caseSetReminder.timerSessionBean = timerSessionBean;
    ThreadM thread = new ThreadM();
    thread.setName("spaces/" + spaceId + "/thread/" + threadId + "");
    Sender sender = new Sender();
    sender.setName("MyName");
    message.setSender(sender);
    message.setThread(thread);
    Reminder reminder = new Reminder("Do Something", ZonedDateTime.now(ZoneId.of("Europe/Athens")).plusMinutes(10),
            "DisplayName", "Europe/Athens", spaceId, threadId);
    reminder.setReminderId(1);
    timerSessionBean.nextReminderDate = reminder.getWhen();
}

它总是抛出我

传递以验证()的论点是type type typersessionbean,不是一个 模拟!

确保正确放置括号!

请参阅正确验证的示例:

verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMethod();

,但这不是真的,它的时间被嘲笑,我的语法是正确的

这就是我运行的方法触发了the each方法

@Test
void mockitoTest() throws Exception {
    final String expectedDate = "12/12/2019 12:00 athens";
    message.setText("remind me ' set next reminder Test' at " + expectedDate);
    request.setMessage(message);
    // Already set in mock a nextReminder that is to be in 10 mins from now()
    //So this should not be set
    caseSetReminder.setRequest(request);
    caseSetReminder.setReminder();
    //Verifies that setNextReminder is called 0 times because Input reminderDate is AFTER the current
    verify(timerSessionBean , times(1)).setNextReminder(Mockito.any(Reminder.class), Mockito.any(ZonedDateTime.class));
}

我希望你们能帮助我弄清楚

您需要确保启动Mockito Engine:

@BeforeEach
final void beforeEach() {
  MockitoAnnotations.initMocks(this);
  ..

 @RunWith(MockitoJUnitRunner.class) 
 public class TestClass{

另外,您无法设置模拟类的字段,例如:

timerSessionBean.nextReminderDate = reminder.getWhen();

尝试使用doReturn()when()then()配置行为

相关内容

  • 没有找到相关文章

最新更新