如何对 void 方法进行 Junit 测试

Pri*_*eja 0 java junit spring

我是 JUnit 测试的新手。你能告诉我如何对 void 方法进行 Junit 测试吗?

我有这个类DemoPublisher和这个demoPublishMessage()返回类型为void的方法。我如何测试这种方法?

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");

    }
}
Run Code Online (Sandbox Code Playgroud)

Flo*_*etz 5

此问题的解决方案称为“模拟”:您可以创建一个“模拟”的 JmsTemplate,将其注入您的类,执行您的方法,然后验证是否调用了模拟的适当方法:

// 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");
    }

}
Run Code Online (Sandbox Code Playgroud)

Mockito 是一个很好的工具,它允许多种方式使用模拟。