テンプレートによるEasyMockTestのシンプル化
3472 ワード
mock template
テストモデル:
テスト・インスタンス
これはajoo投稿のヒントです
/**
* mock template
* @author Jomper
*
*/
public abstract class MockTemplate {
private Object[] mocks;
@Before
public void setUp() throws Exception{
mockFields(getClass(), this);
expectAll();
}
@Test
public void test() {
replay(mocks);
process();
verify(mocks);
}
/**
* reflect itself get annotate fields that dynamic assigned to mock objects
* @param clazz
* @param test
* @throws Exception
*/
private void mockFields(Class<?> clazz, Object test) throws Exception {
List<Object> _mocks = new ArrayList<Object>();
for (Field field : clazz.getDeclaredFields()) {
if (field.getAnnotation(Mock.class) != null) {
try {
field.setAccessible(true);
Object o = createMock(field.getType());
field.set(test, o);
_mocks.add(o);
} catch (IllegalArgumentException e) {
throw new Exception(e.getMessage(),e);
}
}
}
mocks = _mocks.toArray();
}
public abstract void process();
public abstract void expectAll();
}
テストモデル:
/**
* Response interface
* @author Jomper
*
*/
public interface Response {
/**
* request handler
* @param request
* @return result
*/
public Object getResult(Request request);
}
/**
* Request interface
* @author Jomper
*
*/
public interface Request {
/**
* set request content
* @param o
*/
public void setRequest(Object o);
}
/**
* Service sample
* @author Jomper
*
*/
public class Service {
/**
* you can do something before get result
* initial response result and filter special characters from request content
* @param request
* @param response
* @return
*/
public Object execute(Request request, Response response) {
//TODO something before get result
return response.getResult(request);
}
}
テスト・インスタンス
/**
* service test
* @author Jomper
*
*/
public class ServiceTest extends MockTemplate {
@Mock private Request request;
@Mock private Response response;
private Service service;
@Before
public void before() throws Exception{
service = new Service();
}
public void expectAll() throws Exception{
request.setRequest("a cup of tea");
request.setRequest("coffee");
expect(response.getResult(request)).andReturn("Sorry").andReturn("OK");
}
/**
* if request.setRequest("a cup of tea"),response.getResult(request) return "Sorry"
* else return "OK"
*/
public void process() throws Exception{
request.setRequest("a cup of tea");
assertTrue("Sorry".equals(service.execute(request, response)));
request.setRequest("coffee");
assertTrue("OK".equals(service.execute(request, response)));
}
}
これはajoo投稿のヒントです