jeudi 4 juin 2015

Partial mock with Mockito and Spring in Unit testing

I'm trying to mock only a method of a real class, using Spy method from Mockito, but I see that actually the real method has been called and no NullPointerException is raised, as set in the test code with Mockito.doThrow instruction. I'm testing loading Spring context, that's actually used for the application.

Spring version: 4.1.3.RELEASE
Mockito version : 1.8.4

I'm missing something ? Any suggestion in where's the issue ?
Thanks in advance

Test Class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/test-context.xml" })
@ComponentScan(basePackageClasses={MockManager.class})
@ActiveProfiles( profiles = {"test"} )
public class TestPlugin  {
@Autowired
private MockManager manager;
private CamelContext context;
private AtomicInteger idNumber = new AtomicInteger();
private ConnectionFactory jmsConnectionFactory;


@Before
public void init() {
    context = new DefaultCamelContext();

    // activemq broker
    jmsConnectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.deleteAllMessagesOnStartup=true");

    context.addComponent(JMS_ACTIVEMQ_POLLING_COMPONENT, JmsComponent.jmsComponentAutoAcknowledge(jmsConnectionFactory));

    try {
        context.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@After
public void destroy() throws Exception {
    context.stop();     
    context = null;
}



@Test
public void test() throws Throwable {

    manager.init(context, Plugin.class.getCanonicalName(), "/configurations.yaml", 1);

    Plugin d = (Plugin) Mockito.spy(manager.plugin);

    ((Plugin) Mockito.doThrow(new NullPointerException("TEST TO UNDERSTAND IF MOCK METHOD IS CALLED")).when(d)).send((MsgContent) Mockito.any(), (Notification) Mockito.any());

    ProducerTemplate pd = context.createProducerTemplate();

    pd.sendBody(Manager.QUEUE_URI, createMessage());
    Thread.sleep(1000);
    Assert.assertEquals(1, ((Plugin) manager.plugin).getAcceptCount().intValue());
    Assert.assertEquals(1, ((Plugin) manager.plugin).getDeliveryCount().intValue());
    List<Message> rescheduledMsg = manager.getReschduledMessageList();
    Assert.assertEquals(0, rescheduledMsg.size());
}

The Plugin class is essentially like this

@Service("Plugin")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Plugin extends Template<C,F> {

....

public Plugin() {
    super();
    initializePlugin(C.createInstance(this),
            F.createInstance(this));
}


protected Receipt send(final MsgContent msgContent, Notification notification) {
....
....
}

.....


}

Aucun commentaire:

Enregistrer un commentaire