0

I am new to JUnit testing. Can you please tell me how to do Junit Testing for void methods.

I have this class DemoPublisher and this method demoPublishMessage() which has return type void. How can I test this method?

package com.ge.health.gam.poc.publisher;

import javax.jms.JMSException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ge.health.gam.poc.consumer.DemoConsumer;

@Component
public class DemoPublisher {

    @Autowired
    JmsTemplate jmsTemplate;

    public void demoPublishMessage(String message) throws JMSException{
        jmsTemplate.convertAndSend("NewQueue", message);
        System.out.println("Message sent");

    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Priyanka Taneja
  • 157
  • 2
  • 3
  • 13

3 Answers3

5

The solution to this problem is called "mocking": You can create a "mocked" JmsTemplate, inject it into your class, execute your method and then verify that the apropriate method of your mock was called:

// This annotation enables the @Mock, etc. annotations
@RunWith(MockitoJUnitRunner.class)
public class DemoPublisherTest {

    // This creates an instance of this class and then injects all the mocks if possible
    @InjectMocks
    private DemoPublisher demoPublisher;

    // This creates a mocked instance of that class
    @Mock
    private JmsTemplate jmsTemplate;

    @Test
    public void demoPublishMessage_must_call_jmsTemplate_method() {

         // Call the class to test
         this.demoPublisher.demoPublishMessage("test");

         // And now verify that the method was called exactly once with the given parameters
         Mockito.verify( this.jmsTemplate, Mockito.times(1)).convertAndSend(("NewQueue", "test");
    }

}

Mockito is a great tool for that and allows many ways to use mockings.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
0

Use mockito (http://mockito.org/) to mock JmsTemplate. Use verify to check methods were called with given arguments, you can use flexible argument matching, for example any expression via the any() or capture what arguments where called using @Captor instead

Atmega
  • 131
  • 4
0

What you do is you verify the side effects. These are the sending of a message and the output of a String.

You would mock the jmsTemplate and then verify that it got called. If it is actually important to you you would also test the output happens on System.out by mocking and verifying it as well.

There are various mocking libraries available. The one I like best is Mockito

See the documentation of your preferred mocking library for details.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348