2014-01-15 142 views
0

这里是我的服务类的JUnit Spring MVC的服务方法返回类型为void

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() { 
     logger.info("initializing..."); 
     System.out.println("INIT"); 
     messageChannel.subscribe(this); 
    } 

    @Override 
    public void handleMessage(Message<?> message) throws MessagingException { 
     logger.info("Message: " + message); 

    } 
} 

因为我想创建一个JUnit测试案例初始化。怎么写?

这是我试过的。但它不工作

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration("classpath:webapptest") 
@ContextConfiguration(locations = {"classpath:test-applicationcontext.xml"}) 
public class EmailServiceTest { 

    @Autowired 
    private EmailService emailService; 

    @Test(timeout=600000) 
    public void testEmailService() throws Exception { 
     emailService=Mockito.spy(emailService); 
     Mockito.doNothing().when(emailService).init(); 
    } 
} 

在控制台它不打印在init()方法记录器或打印语句。

我在做什么错误?如何编写测试用例?

回答

1

在你的测试中,你没有叫init()。没有您拨打init()方法,它将不会执行Mockito.doNothing().when。就你的代码而言,init()方法只是一个普通的公共方法。

如果您确实希望在类实例化后调用init()方法,则必须使用@PostConstruct注释对其进行注释。

您的测试应该是这样的下面

@Test(timeout=600000) 
public void testEmailService() throws Exception { 
..... 
     emailService.init(); 
} 

你将不得不打电话emailService.init(),因为你已经创建了一个间谍;为测试工作。目前你并没有测试任何东西,只是在你的测试方法中有一堆Mocks。 另外,一个全面的测试将是您验证在测试init方法时是否调用messageChannle.subscribe()方法的地方。 您确实希望通过验证subscribe()方法是否被调用来加强您的测试。

+0

谢谢。我如何验证? – iCode

+0

我加了上面的。它仍然不打印任何东西 – iCode

+0

@iProgrammer那么,你告诉它什么都不做。印刷会做点什么,不是吗? –

相关问题