junit 4パラメータ化テストとeasymockの使用


junit 4のいくつかの新しい特性を利用して、複数のパラメータを簡単にテストすることができます.次に、数値和を計算する例を挙げます.
package com.test.junit4;

import java.util.Arrays;  
import java.util.Collection;  
  
import org.junit.Assert;  
import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.junit.runners.Parameterized;  
import org.junit.runners.Parameterized.Parameters;  
/** 
 *  Parameterized  
 * 
 */  
@RunWith(Parameterized.class)  
public class AddTest3 {  
  
    private int input1;  
    private int input2;  
    private int expected;  
      
    /** 
     *  。 , : 
 
         1) Parameters  
         2) public static  
         3) Collection  
         4)  
         5)  
     * @return 
     */
    @Parameters  
    @SuppressWarnings("unchecked")  
    public static Collection prepareData(){  
        Object [][] object = {{-1,-2,-3},{0,2,2},{-1,1,0},{1,2,3}};  
        return Arrays.asList(object);
    }  
    
    public AddTest3(int input1,int input2,int expected){  
        this.input1 = input1;  
        this.input2 = input2;  
        this.expected = expected;  
    }  
    @Test  
    public void testAdd(){  
        Add add = new Add();  
        int result = add.add(input1, input2);  
        Assert.assertEquals(expected,result);  
    }  
    
    class Add{
    	public int add(int a,int b){  
    		return a+b;  
    	}  
    }
}
 
junit 4とeasymockを組み合わせて、私は自分のコードのためにテストクラスを書きました.
私の元のプログラムはHttpServeretRequestからパラメータを取得し、計算結果をsockeで要求を送信してから要求を受け入れます.コードは以下の通りです.
package com.movellsoft.ideal.manufacturer.diagnostics.web;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.movellsoft.ideal.core.web.Struts2Action;
import com.movellsoft.ideal.manufacturer.diagnostics.socket.ClientTCPSocket;


@SuppressWarnings("serial")
public class DiagnosticsRemoteAction extends Struts2Action implements ServletRequestAware{
	
	private static Logger log = Logger.getLogger(DiagnosticsRemoteAction.class);
	private HttpServletRequest request;
	private ClientTCPSocket socket;
	
	public void setSocket(ClientTCPSocket socket) {
		this.socket = socket;
	}

	public String remoteDiag(){
		log.debug("<<< reomoteDiag <<< ");
		String conn 		= request.getParameter("connect");
		String connValue 	= request.getParameter("ConnectValue");
		String dtype 		= request.getParameter("data_type");
		String display 		= request.getParameter("display");
		String rtime 		= request.getParameter("realtime");
		String proname 		= request.getParameter("process_name");
		String allsr		= request.getParameter("all_stacks_regs");
		boolean flag400 = allsr.equals("1");
//		System.out.println("---------------------------all stack & register :: "+ allsr);
		//String modulename = request.getParameter("module_name");
		
		if(conn == null || "".equals(conn)){
			request.setAttribute("msg", getText("connect.notnull"));
			log.debug("conn");
			return SUCCESS;
		}
		if(!conn.equals("cable") && (connValue == null || "".equals(connValue))){
			request.setAttribute("msg", getText("convalue.notnull"));
			log.debug("connValue");
			return SUCCESS;
		}
		if(dtype == null || "".equals(dtype)){
			request.setAttribute("msg", getText("dtype.notnull"));
			log.debug("dtype");
			return SUCCESS;
		}
		log.debug("check filed over");
		
		// byte 
		
		//16 01
		byte[] bts = new byte[128];
		for (int i = 0; i < 16; i++) {
			bts[i] = 1;
		}
		
		//02,D0,01
		bts[16] = 2;
		bts[17] = -48;
		for (int j = 18; j < 22 ; j++) {
			bts[j] = 0;
		}
		bts[22] = 1;
		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		String ip = addr.getHostAddress();
		
		if(conn.equals("ip")){
			ip = connValue;
		}
		log.debug("<<< ip == "+ip);
		
		//ip length
		bts[23] = (byte)ip.length();
		byte[] btip = ip.getBytes();
		int length = btip.length;
		int j = 24;
		
		//ip
		for (int i = 0 ; i < length; i++,j++) {
			bts[j] = btip[i]; 
		}
		////////////////////// 
		
		
		//sender SMS 0,cable 1[4]
		for(int i=0;i<3;i++){
			bts[j++]=0;
		}
		if(conn.equals("ip")){
			log.debug("ip");
			bts[j++]=0;
		}
		else if(conn.equals("cable")){
			bts[j++]=1;
		}
		//operation [4]
		log.debug("dtype=["+dtype+"]");
		if(dtype.equals("lastreport")){
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=2;
		}
		else if(dtype.equals("allreport")){
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=1;
		}
		else if(dtype.equals("realtime")){
			if(rtime.equals("sysdata")){
				if(flag400){
					bts[j++]=0;
					bts[j++]=4;
					bts[j++]=0;
					bts[j++]=0;
				}
				else{
					bts[j++]=0;
					bts[j++]=0;
					bts[j++]=0;
					bts[j++]=0;
				}
			}
			else if(rtime.equals("f")){
				bts[j++]=2;
				bts[j++]=0;
				bts[j++]=0;
				bts[j++]=0;
			}
			else if(rtime.equals("m")){
				if(flag400){
					bts[j++]=4;
					bts[j++]=4;
					bts[j++]=0;
					bts[j++]=0;
				}else{
					bts[j++]=4;
					bts[j++]=0;
					bts[j++]=0;
					bts[j++]=0;
				}
			}
			else if(rtime.equals("mandf")){
				bts[j++]=6;
				bts[j++]=0;
				bts[j++]=0;
				bts[j++]=0;
			}
			/***********************[ new ]******************************/
			else if(rtime.equals("oneProcess")){
				if(flag400){
					bts[j++]=(byte)128;
					bts[j++]=4;
					bts[j++]=0;
					bts[j++]=0;
				}else{
					bts[j++]=(byte)128;
					bts[j++]=0;
					bts[j++]=0;
					bts[j++]=0;
				}
			}
			else if(rtime.equals("oneModule")){
				if(flag400){
					bts[j++]=0;
					bts[j++]=6;
					bts[j++]=0;
					bts[j++]=0;
				}else{
					bts[j++]=0;
					bts[j++]=2;
					bts[j++]=0;
					bts[j++]=0;
				}
			}
			else if(rtime.equals("all_history")){
				if(flag400){
					bts[j++]=0;
					bts[j++]=5;
					bts[j++]=0;
					bts[j++]=0;
				}else{
					bts[j++]=0;
					bts[j++]=1;
					bts[j++]=0;
					bts[j++]=0;
				}
			}
			else if(rtime.equals("all_stacks_regs")){
				bts[j++]=0;
				bts[j++]=4;
				bts[j++]=0;
				bts[j++]=0;
			}
			/***********************[ new ]******************************/
		}
		
		//display 0 popup,1 nopopup[4]
		
		if(display.equals("nopopup")){
			log.debug("nopopup");
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=0;
		}
		else if(display.equals("popup")){
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=1;
		}
		
		//processname or module name length [4]
		if(proname != null && !"".equals(proname)){
			bts[j++]=(byte)proname.length();
			bts[j++]=0;
			bts[j++]=0;
			bts[j++]=0;
			//processname or module name
			byte[] pn = proname.getBytes();
			for(int i=0;i<pn.length;i++){
				bts[j++]=pn[i];
			}
		}
		byte[] bts2 = new byte[j++];
		for (int i = 0; i < bts2.length; i++) {
			bts2[i] = bts[i];
		}

		log.debug("bts2 length is "+bts2.length+" :");
		String d="";
		for(int i=0;i<bts2.length;i++){
			if(i%16==0)d+="
"; int v = bts2[i] & 0xFF; if (v < 16) d += "0"; d += Integer.toString(v, 16).toUpperCase() + " "; } log.debug("<<<d : "+d); System.out.println(d); // socket if(!socket.open(ip,"6789")){ request.setAttribute("msg", getText("socket.error")); log.debug("<<<< msg:"+request.getAttribute("msg")); return SUCCESS; } // request if(socket.send(bts2) == -2){ request.setAttribute("msg", getText("socket.error")); log.debug("<<<< msg:"+request.getAttribute("msg")); return SUCCESS; } socket.close(); request.setAttribute("msg", getText("request.succeed")); log.debug("<<<< msg:"+request.getAttribute("msg")); return SUCCESS; } public String localDiag(){ log.debug("<<< localDiag <<<"); String serverpath = request.getParameter("serverpath"); File serverf = new File(serverpath); if(serverf.exists()){ }else{ request.setAttribute("msg", getText("file.notexist")); } return SUCCESS; } public String remotepage(){ return SUCCESS; } public void setServletRequest(HttpServletRequest request) { this.request = request; } public static void main(String[] args) { byte[] bts2 = new byte[16]; ByteBuffer bytebuf = ByteBuffer.wrap(bts2); bytebuf = bytebuf.order(ByteOrder.LITTLE_ENDIAN); bytebuf.putInt(12); bytebuf.putInt(15); bytebuf.putChar('a'); bytebuf.putChar('b'); bytebuf.put((byte)1); bytebuf.put((byte)2); bts2 = bytebuf.array(); for (int i = 0; i < bts2.length; i++) { byte b = bts2[i]; System.out.print(String.valueOf(b)+"
"); } } }

 
easymockとパラメトリックテストを利用して、私が書いたテストクラスです.
package com.movellsoft.ideal.manufacturer.diagnostics.web;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.movellsoft.ideal.manufacturer.diagnostics.socket.ClientTCPSocket;

import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;

@RunWith(Parameterized.class)
public class TestRemoteAction {
	
	private IMocksControl control = EasyMock.createControl();
	private HttpServletRequest request = control.createMock(HttpServletRequest.class);
	private DiagnosticsRemoteAction rAction = new DiagnosticsRemoteAction();
	private ClientTCPSocket socket = null;
	
	private String realtime;
	private String all_st_reg;
	
	
	public TestRemoteAction(String realtime,String all_st_reg) {
		System.out.println(realtime+ " " +all_st_reg);
		this.realtime = realtime;
		this.all_st_reg = all_st_reg;
	}
	
	@SuppressWarnings("unchecked")
	@Parameters
	public static Collection prepareData(){
		Object [][] obs = {
			{"sysdata","0"},
			{"sysdata","1"},
			{"m","0"},
			{"m","1"},
			{"oneModule","0"},
			{"oneModule","1"},
			{"oneProcess","0"},
			{"oneProcess","1"},
			{"all_history","0"},
			{"all_history","1"},
			{"all_stacks_regs","0"},
			{"all_stacks_regs","1"}
		};
		return Arrays.asList(obs);
	}
	
	@Test
	public void exec(){
		request.getParameter("connect");
		expectLastCall().andReturn("cable");
		request.getParameter("ConnectValue");  
		expectLastCall().andReturn("");
		request.getParameter("data_type");
		expectLastCall().andReturn("realtime");
		request.getParameter("display");
		expectLastCall().andReturn("nopopup");
		request.getParameter("realtime");
		expectLastCall().andReturn(realtime);
		
		request.getParameter("process_name");
		expectLastCall().andReturn("");
		request.getParameter("all_stacks_regs");
		expectLastCall().andReturn(all_st_reg);
		
		try {
			socket = createMock(ClientTCPSocket.class,new Method[]{
				ClientTCPSocket.class.getMethod("open",String.class,String.class),
				ClientTCPSocket.class.getMethod("send", byte[].class)
			});
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		}
		
		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		String ip = addr.getHostAddress();
		
		expect(socket.open(ip,"6789")).andReturn(true);
		
		expect(socket.send((byte[])anyObject())).andReturn(1);
		
		socket.close();
		
		request.setAttribute("msg", rAction.getText("request.succeed"));
		request.getAttribute("msg");
		expectLastCall().andReturn("");
		
		replay(socket);
		control.replay();
		/**********************/

		rAction.setServletRequest(request);
		rAction.setSocket(socket);
		rAction.remoteDiag();
		
		/***********************/
		control.verify();
		verify(socket);
	}
	
	@After
	public void line(){
		if("1".equals(all_st_reg))
		System.out.println("--------------------------------------------------------");
	}

}
 
junitで実行する出力は次のとおりです.
sysdata 0
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 00 00 00 00 00 00 00 00 sysdata 1
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 00 04 00 00 00 00 00 00 --------------------------------------------------------m 0
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 04 00 00 00 00 00 00 00 m 1
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 04 04 00 00 00 00 00 00 --------------------------------------------------------oneModule 0
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 00 02 00 00 00 00 00 00 oneModule 1
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 00 06 00 00 00 00 00 00 --------------------------------------------------------oneProcess 0
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 80 00 00 00 00 00 00 00 oneProcess 1
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 80 04 00 00 00 00 00 00 --------------------------------------------------------all_history 0
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 00 01 00 00 00 00 00 00 all_history 1
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 D0 00 00 00 00 01 0C 31 39 32 2E 31 36 38 2E 30 2E 31 37 00 00 00 01 00 05 00 00 00 00 00 00 --------------------------------------------------------
junitは結果を表示します: