Junit test with mock

时间:2024-11-09 10:20:45

package gradletst.biz;

import java.util.Random;

public class IdGenerator {

public static String generateId() {

Random r=new Random();

String id = Integer.valueOf(r.nextInt()).toString() ;

return id;

}

public String wrap(String id) {

return "id:'"+id+"'";

}

}

package gradletst.biz;

import java.io.UnsupportedEncodingException;

public class GroupGenerator {

String defaultName = "blue";

public String genGroupName() throws UnsupportedEncodingException {

return defaultName;

}

public String wrapGroup(String name) {

return "name:'" + name+"'";

}

}

package gradletst.biz;

public class FullNameIntegrator {

public String createStatement(String group,String id ) {

return group + " " +id ;

}

}

package gradletst.biz;

import java.text.SimpleDateFormat;

import java.util.Date;

public class JobWrapper {

public String wrap(String sts) {

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

String dt= sdf.format(new Date())+":";

return dt +" Job ["+sts +"] is running happily!";

}

}

package gradletst.biz;

public class RunJob {

public void run(String sts) {

System.out.println("Start job ...");

System.out.println(sts);

System.out.println("End job ...");

}

}

package gradletst.biz;

import java.io.UnsupportedEncodingException;

public class JobManager {

RunJob job=new RunJob();

FullNameIntegrator svc =new FullNameIntegrator();

GroupGenerator nameGen=new GroupGenerator();

JobWrapper wrapper =new JobWrapper();

public void run() throws UnsupportedEncodingException {

String id =IdGenerator.generateId();

IdGenerator idGen = new IdGenerator();

String wrapId = idGen.wrap(id);

String group=nameGen.genGroupName();

String wrapGroup =nameGen.wrapGroup(group);

String sts= svc.createStatement(wrapGroup, wrapId);

String wrapSts = wrapper.wrap(sts);

job.run(wrapSts);

}

public RunJob getJob() {

return job;

}

public void setJob(RunJob job) {

this.job = job;

}

public FullNameIntegrator getSvc() {

return svc;

}

public void setSvc(FullNameIntegrator svc) {

this.svc = svc;

}

}