2014-01-15 73 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那麼,你告訴它什麼都不做。印刷會做點什麼,不是嗎? –

相關問題