我有一个 Java Spring MVC 应用程序。这是我的服务类。
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.Message;
import org.springframework.integration.MessagingException;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageHandler;
import org.springframework.stereotype.Service;
@Service
public class EmailService implements MessageHandler {
@Autowired
@Qualifier("receiveChannel")
private DirectChannel messageChannel;
private final Log logger = LogFactory
.getLog(EmailService.class);
public void init() {
messageChannel.subscribe(this);
}
@Override
public void handleMessage(Message<?> message) throws MessagingException {
logger.info("Message: " + message);
}
}
我想为上面的类编写一个测试用例。这是我尝试过的
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
//other imports
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("classpath:webapptest")
@ContextConfiguration(locations = {"classpath:test-applicationcontext.xml"})
public class EmailServiceTest {
@Autowired
private EmailService emailService;
@Autowired
WebApplicationContext wContext;
@Test
public void testEmailService() throws Exception {
emailService=Mockito.spy(new EmailService());
Mockito.doNothing().when(emailService).init();
}
}
在我的 applicationcontext.xml 中,我指定了一个 Gmail 及其密码(其 IMAP 访问已启用)
当我从其他邮件发送该邮件中的一些消息时,它应该只记录该消息(在 Service 类的其他方法中实现)
当我运行测试用例时,它显示测试用例成功。但是,当我向该邮件 ID 运行任何消息时,它不会在我的控制台中打印。
最佳答案
为什么要加载上下文?如果这不是集成测试,则不需要集成测试(请记住单元测试需要快速并且不加载/连接到外部资源)。
无论如何,我建议您使用 Mockito
来模拟 DirectChannel
并验证交互。
以下是我测试 init()
方法的方法:
public class EmailServiceTest {
@Mock
DirectChannel messageChannel;//you
@InjectMocks
EmailService emailService;
@Test
public void shouldSubscribeToSelf(){
//call method under test
emailService.init();
//verify behavior
Mockito.verify(messageChannel).subscribe(emailService);
}
}
关于java - Spring MVC 服务 Junit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21132487/