我们使用plexus测试用例代替junit测试用例,前者建立plexus容器接口以便部署时允许我们的组件执行。
需要注意的是,如果我们重载setUp()和tearDown()方法去添加一些通用功能或清理功能,那么我们需要确保调用super.xxx()方法,否则,我们就需要注意plexus容器实例的初始化和清除操作了。
以下是一个基本的组件测试用例:
package org.codehaus.plexus.tutorial; import java.net.UnknownHostException; import org.codehaus.plexus.PlexusTestCase; /** * Basic test. */ public class WebsiteMonitorTest extends PlexusTestCase { /** * sets up a Plexus container instance for running test. */ protected void setUp() throws Exception { // call this to enable super class to setup a Plexus container test // instance and enable component lookup. super.setUp (); } /** * Test if we are able to lookup and obtain our component instance from the * container. * * @throws Exception */ public void testBasic() throws Exception { WebsiteMonitor component = (WebsiteMonitor) lookup (WebsiteMonitor.ROLE); assertNotNull (component); } /** * Test an unkown host. * * @throws Exception */ public void testUnknownHost() throws Exception { WebsiteMonitor component = (WebsiteMonitor) lookup (WebsiteMonitor.ROLE); assertNotNull (component); Exception e = null; try { component.monitor ("http://www.yadayadayda.com/"); } catch (Exception e1) { e = e1; } assertNotNull (e); assertEquals (true, (e instanceof UnknownHostException)); } /** * Test a page that does not exists. * * @throws Exception */ public void testNotOKCode() throws Exception { WebsiteMonitor component = (WebsiteMonitor) lookup (WebsiteMonitor.ROLE); assertNotNull (component); Exception e = null; try { component.monitor ("http://www.google.co.nz/unknown_404_.html"); } catch (Exception e1) { e = e1; } assertNotNull (e); } }
在eclipse中yunxing单元测试,如所料,出现异常了。以下是monitor的具体实现代码(我们更新DefaultWebsiteMonitor类继承org.codehaus.plexus.logging.AbstractLogEnabled代替了第一版的system.out来实例化容器的org.codehaus.plexus.logging.Logger)
public class DefaultWebsiteMonitor extends AbstractLogEnabled implements WebsiteMonitor {