gpt4 book ai didi

java - 如何对 void 方法进行 Junit 测试

转载 作者:行者123 更新时间:2023-12-01 16:53:57 24 4
gpt4 key购买 nike

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

}
}

最佳答案

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

// 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 是一个很棒的工具,它允许通过多种方式使用模拟。

关于java - 如何对 void 方法进行 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com