对通过guice注入的模拟(带有Mockito)对象使用验证 [英] use verify on mocked (with Mockito) objects inject by guice

查看:228
本文介绍了对通过guice注入的模拟(带有Mockito)对象使用验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有单元测试,我将guice用于di,我用:注释我的班级

I have unit test, i use guice for di, i annotate my class with :

@Guice(modules = { BatchGuiceModule4Test.class })
public class TestOneDayBatchStarter {
}

我的对象像这样从我的模块中很好地注入了:

My objects are well injected from my module like this one :

@Inject
private DataManager dataManager;

在我的模块中,我添加了一个@Provides方法:

In my module, I add a @Provides method :

@Provides
@Singleton
public DataManager getDataManager() {
    LOG.debug("## init Mocked Data Manager");
    DataManager dataManager = mock(DataManager.class);
    when(dataManager.getObjectCodeList()).thenReturn(getOcList());
        ....
return dataManager;
}

在我的测试中,我调用了一种方法,该方法称为特定方法,并且我想对其进行验证:

And in my test, i call a method which called a specific method and i want to verify it :

@Test
public void testDefaultJob() {
    JobDetail jobDetail = newJob().ofType(OneDayBatchStarter.class)
            .withIdentity(DAILY_DEFAULT_JOB, Scheduler.DEFAULT_GROUP).build();
    try {
        scheduler.scheduleJob(jobDetail, TriggerBuilder.newTrigger().startNow().build());
    } catch (SchedulerException e) {
        LOG.warn("error during scheduling", e);
    }
    verify(dataManager).getObjectCodeList();
}

我添加了一些跟踪信息,我看到模拟对象实际上是这样称呼的:

I add some trace, i see that mocked object was actually called like :

"## init Mocked Data Manager "

"Call object code list ....."

但是我在验证时出错:

FAILED: testDefaultJob
Wanted but not invoked:
dataManager.getObjectCodeList();
-> at net.test.batch.TestOneDayBatchStarter.testDefaultJob(TestOneDayBatchStarter.java:177)
Actually, there were zero interactions with this mock.

我错过了什么吗,还是无法通过Guice使用Mockito验证?

Did i miss something, or it's not possible to use mockito verify through Guice ?

推荐答案

PEBKAC问题,Guice和Mockito完美地工作了,只是我用石英启动了工作,所以石英在新线程中启动了工作.不用等待,我检查我的嘲笑对象是否已经被调用,所以是我的问题.

PEBKAC problem, Guice and Mockito works perfectly, it's just that i launch job with quartz, so quartz launch the job in a new thread. And without waiting, i check if my mocked object were already called, so my problem.

所以我改变了我的测试方法

So i change my test method with this

@Test
public void testDefaultJob() throws InterruptedException, Exception {
    JobDetail jobDetail = newJob().ofType(OneDayBatchStarter.class)
            .withIdentity(DAILY_DEFAULT_JOB, Scheduler.DEFAULT_GROUP).build();
    scheduler.scheduleJob(jobDetail, TriggerBuilder.newTrigger().startNow().build());
    Thread.currentThread().sleep(500);
    while (!scheduler.getCurrentlyExecutingJobs().isEmpty()) {
        Thread.currentThread().sleep(500);
    }
    verify(dataManager).getObjectCodeList();
}

这篇关于对通过guice注入的模拟(带有Mockito)对象使用验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆