现在的位置: 首页 > 综合 > 正文

4、JUnit使用的设计模式

2018年02月05日 ⁄ 综合 ⁄ 共 8505字 ⁄ 字号 评论关闭

JUnit源代码涉及使用了大量设计模式

1、模板方法模式(Template Method):定义一个操作中的算法骨架,而将一些步骤延伸到子类中去,使得子类可以不改变一个算法的结构,即可重新定义该算法的某些特定步骤。这里需要复用的是算法的结构,也就是步骤,而步骤的实现可以在子类中完成。

      使用场合:a)一次性实现一个算法的不变部分,并且将可变的行为留给子类来完成。b)各子类公共的行为应该被提取出来并集中到一个公共父类中以避免代码的重复。首先识别现有代码的不同之处,并且把不同部分分离为新的操作,最后,用一个调用这些新的操作的模板方法来替换这些不同的代码。c)控制子类的扩展

      模板方法模式的组成:

      —父类角色:提供模板
      —子类角色:为模板提供实现

父类角色,必须是抽象类,定义特定的步骤:

public abstract class AbstractClass
{
	public void template()
	{
		this.method1();
		this.method2();
		this.method3();
	}
	
	public abstract void method1();
	public abstract void method2();
	public abstract void method3();
	
}

template()方法规定了具体的步骤,必须是先执行method1,在执行method2,最后method3
子类角色,为模板提供实现:

public class ConcreteClass extends AbstractClass
{
	@Override
	public void method1()
	{
		System.out.println("step1");
	}

	@Override
	public void method2()
	{
		System.out.println("step2");
	}

	@Override
	public void method3()
	{
		System.out.println("step3");
	}

}

最后测试一下:

public class client
{
	public static void main(String[] args)
	{
		AbstractClass ac = new ConcreteClass();
		ac.template();
	}
}

在JUnit中对应上述三个方法的就是JUnit3中的setUp、testMethod(测试方法)、tearDown和JUnit4中的@Before、@Test、@After

JUnit3.8中的源代码:TestCase.java

其中的runBare()方法

public void runBare() throws Throwable {
        setUp();
        try{
                runTest();
        }
        finally {
                tearDown();
        }
}

使用了模板方法模式。

2、适配器模式(Adapter)

在软件系统中,由于应用环境的变化,常常需要将“一些现存的对象”放在心的环境中应用,但是新环境要求的接口是这些现存对象所不满足的,那么如何应对这种“迁移的变化”?如何既能利用现有对象的良好实现,同时又能满足新的应用环境所要求的接口?这就是Adapter模式要解决的。

- 意图:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

- 适配器(Adapter)模式的构成:
    -目标抽象角色(Target)——定义客户要用的特定领域的接口
    -适配器(Adapter)——调用另一个接口,作为一个转换器
    -适配器(Adaptee)——定义一个接口,Adapter需要接入
    -客户端(Client)——协同对象符合Adapter适配器

有三种类型的适配器模式:
    -类适配器(采取继承的方式)
    -对象适配器(采取对象组合的方式)——推荐使用
    -缺省的适配器模式

适用性:
    -对象需要利用现存的并且接口不兼容的类。
    -需要创建可重用的类以协调其他接口可能不兼容的类

举例:1、采取继承的方式实现Adapter模式:

public interface Target
{
	public void method1();
}


public class Adaptee
{
	public void method2()
	{
		System.out.println("目标方法");
	}
}

public class Adapter extends Adaptee implements Target
{
	@Override
	public void method1()
	{
		this.method2();
	}
}

public class Client
{
	public static void main(String[] args)
	{
		Target target = new Adapter();
		target.method1();
	}
}

注意Adapter类,他继承了现有类Adaptee并且实现了我们所要求的特定接口Target。

对于JUnit框架,适配模式体现在TestCase中的runTest()方法:

protected void runTest() throws Throwable {
		assertNotNull(fName);
		Method runMethod= null;
		try {
			// use getMethod to get all public inherited
			// methods. getDeclaredMethods returns all
			// methods of this class but excludes the
			// inherited ones.
			runMethod= getClass().getMethod(fName, null);
		} catch (NoSuchMethodException e) {
			fail("Method \""+fName+"\" not found");
		}
		if (!Modifier.isPublic(runMethod.getModifiers())) {
			fail("Method \""+fName+"\" should be public");
		}

		try {
			runMethod.invoke(this, new Class[0]);
		}
		catch (InvocationTargetException e) {
			e.fillInStackTrace();
			throw e.getTargetException();
		}
		catch (IllegalAccessException e) {
			e.fillInStackTrace();
			throw e;
		}
	}

在runBare方法中,通过runTest方法将我们自己编写的testXXX方法进行了适配,使得JUnit可以执行我们编写的TestCase

在runTest方法中,首先获得我们自己编写的testXXX方法所对应的Method对象(不带参数),然后检查该Method所对应的方法是否是public的,如果是则调用Method对象的invoke方法来执行我们自己编写的testXXX方法。

举例:2、采取对象组合方式使用Adapter模式

public interface Target
{
	public void method1();
}

public class Adaptee
{
	public void method2()
	{
		System.out.println("执行方法" );
	}
}

public class Adapter implements Target
{
	private Adaptee adaptee;
	public Adapter(Adaptee adaptee)
	{
		this.adaptee = adaptee;
	}
	@Override
	public void method1()
	{
		adaptee.method2();
	}
}

public class Client
{
	public static void main(String[] args)
	{
		Target target = new Adapter(new Adaptee());
		target.method1();
	}
}

与继承方式不同处就在于Adapter。

举例:3、缺省的适配器模式(就是在AWT、Swing事件模型中使用的适配器模式)

public interface AbstractService
{
	public void service1();
	public void service2();
	public void service3();
}

public class ServiceAdapter implements AbstractService
{
	@Override
	public void service1()
	{
		
	}
	@Override
	public void service2()
	{
		
	}
	@Override
	public void service3()
	{
		
	}
}

public class ConcreteService extends ServiceAdapter
{
	@Override
	public void service1()
	{
		System.out.println("执行业务方法");
	}
}

AWT的举例:

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class AwtApp
{
	public static void main(String[] args)
	{
		Frame frame = new Frame("title");
		frame.addMouseMotionListener(new MouseMotionAdapter()
		{
			@Override
			public void mouseMoved(MouseEvent e)
			{
				System.out.println("x:" + e.getX() + "y:" + e.getY());
			}
		});
		frame.addWindowListener(new WindowAdapter()
		{
			@Override
			public void windowClosing(WindowEvent e)
			{
				System.out.println("close window");
				System.exit(0);
			}
		});
		frame.setSize(new Dimension(200,400));
		frame.setVisible(true);
	}
}

3、命令(Command)模式

JUnit是一个测试framework,测试人员只需要开发测试用例,然后把这些测试用例(TestCase)组成请求(可能是一个或多个),发送到JUnit执行,最后报告详细测试结果。其中包括执行的时间,错误方法,错误位置等。这样测试用例的开发人员就不需要知道JUnit内部的细节,只奥符合它定义的请求格式即可。从JUnit的角度考虑,他并不需要知道请求TestCase的具体操作信息,仅把它当做一种命令来执行,然后把执行测试结果发给测试人员。这样就使JUnit框架和TestCase的开发人员独立开来,使得请求的一方不必知道接收请求一方的详细信息,更不必知道是怎样被接收,以及怎样被执行的,实现系统的松耦合。

Command模式的意图是:将一个请求封装成一个对象,从而使你可用不同的请求对客户进行参数化;对请求进行排队或记录请求日志,Command模式告诉我们可以为一个操作生成一个对象并给出他的一个“excute(执行)”方法。

命令模式的构成:
1)客户角色:创建一个具体命令对象,并确定其接收者
2)命令角色:声明一个给所有具体命令类的抽象接口。这是一个抽象角色,通常由一个接口或抽象类实现
3)具体命令角色:定义一个接收者和行为之间的弱耦合,实现execute方法,负责调用接受者的相应操作
4)请求者角色:负责调用命令对象执行请求
5)接收者角色:负责具体实施和执行一个请求

 

public interface Command
{
	public void execute();
}

public class Receiver
{
	public void doAction()
	{
		System.out.println("执行操作");
	}
}

public class ConcreteCommand implements Command
{
	private Receiver receiver;
	public ConcreteCommand(Receiver receiver)
	{
		this.receiver = receiver;
	}
	@Override
	public void execute()
	{
		receiver.doAction();
	}
}

public class Invoker
{
	private Command command;
	public Invoker(Command command)
	{
		this.command = command;
	}
	public void doInvokerAction()
	{
		command.execute();
	}
}

public class Client
{
	public static void main(String[] args)
	{

		Receiver receiver = new Receiver();
		Command command = new ConcreteCommand(receiver);
		Invoker invoker = new Invoker(command);
		invoker.doInvokerAction();
	}
}

 

在命名模式下,最终的执行者是接收者(Receiver),它来执行操作,Receiver执行什么样的操作由具体命令(ConcreteCommand)来指出,具体命令的execute方法中指出了接受者要执行的动作(如果Receiver中包含不止一种方法,那么Command的execute可以指定调用哪一个方法,即receiver.doAction()),命令和接受者之间有弱耦合(通过具体命令ConcreteCommand中包含一个对接受者Receiver的引用),也就是说命令知道他最终的执行者是谁,那么命令怎样才能被执行呢(即谁来下达命令呢),这就是请求者(调用者)Invoker来做的工作,它与Command之间有一个弱耦合,Invoker调用command(也就是command的execute方法)。

4、组合(Composite)模式

组合模式有时又叫部分-整体模式,它使我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。

意图:将对象组合成为树形结构以表示“部分-整体”的层次结构。Composite模式使得用户对单个对象和组合对象的使用具有一致性

组合对象的构成:
-Component(抽象构建接口):为组合的对象声明接口;在某些情况下实现从此接口派生出的所有类共有的默认行为;定义一个接口可以访问及管理它的多个子部件
-Leaf(叶部件):在组合中表示叶节点对象,叶节点没有子节点;定义组合中接口对象的行为
-Composite(组合类):定义有子节点(子部件)的部件的行为;存储子节点(子部件);在Component接口中实现与子部件相关的操作
-Client(客户端):通过Component接口控制组合部件的对象

举例:组合模式第一种实现

public interface Component
{
	public void doSomething();
}

public class Leaf implements Component
{

	@Override
	public void doSomething()
	{
		System.out.println("执行方法");
	}

}

import java.util.ArrayList;
import java.util.List;

public class Composite implements Component
{
	private List<Component> list = new ArrayList<Component>();
	public void add(Component component)
	{
		list.add(component);
	}
	public void remove(Component component)
	{
		list.remove(component);
	}
	public List<Component> getAll()
	{
		return this.list;
	}
	@Override
	public void doSomething()
	{
		for(Component component : list)
		{
			component.doSomething();
		}
	}

}

public class Client
{
	public static void main(String[] args)
	{
		Component leaf1 = new Leaf();
		Component leaf2 = new Leaf();
		
		Composite comp1 = new Composite();
		comp1.add(leaf1);
		comp1.add(leaf2);
		
		Component leaf3 = new Leaf();
		Component leaf4 = new Leaf();
		
		Composite comp2 = new Composite();
		
		comp2.add(comp1);
		comp2.add(leaf3);
		comp2.add(leaf4);
		
		comp2.doSomething();
	}
}

Leaf相当于我们写的TestCase,Composite相当于TestSuite

举例:组合模式第二种实现,将管理功能提升到接口里面,对Composite没有影响,对Leaf有影响,因为Leaf没有添加删除返回功能,所以空实现

import java.util.List;

public interface Component
{
	public void doSomething();
	public void add(Component component);
	public void remove(Component component);
	public List<Component> getAll();
}

import java.util.ArrayList;
import java.util.List;

public class Composite implements Component
{
	private List<Component> list = new ArrayList<Component>();
	
	@Override
	public void add(Component component)
	{
		list.add(component);
	}

	@Override
	public void doSomething()
	{
		for(Component component : list)
		{
			component.doSomething();
		}
	}

	@Override
	public List<Component> getAll()
	{
		return this.list;
	}

	@Override
	public void remove(Component component)
	{
		list.remove(component);
	}

}


import java.util.List;

public class Leaf implements Component
{
	@Override
	public void add(Component component)
	{

	}

	@Override
	public void doSomething()
	{
		System.out.println("zhixing");
	}

	@Override
	public List<Component> getAll()
	{
		return null;
	}

	@Override
	public void remove(Component component)
	{

	}

}

组合模式有两种实现方式:

1)将管理子元素的方法定义在Composite类中;
2)将管理子元素的方法定义在Component接口中,这样Leaf类就需要对这些方法空实现。

5、JUnit中要区分错误(error)与失败(failure)
1)错误指的是代码中抛出了异常等影响代码正常执行的情况,比如抛出了ArrayIndexOutOfBoundsException,这叫做错误
2)失败指的是我们断言所期待的结果与程序实际执行的结果不一致,或者是直接调用了fail()方法,这叫失败

6、对于测试类来说,如果一个测试类中有5个测试方法,那么JUnit就会创建5个测试类的对象,每一个对象只会调用一个测试方法(为了符合命令模式的要求),在添加方法之前,需要首先判断测试方法是否满足public、void、no-arg、no-return这些条件,如果满足则添加到集合当中准备作为测试方法来去执行。

 

 

抱歉!评论已关闭.