有时需要对某个方法进行单元测试,但其传参是HttpServletRequest类型,这时便须使用代码new一个HttpServletReques对象。
因为HttpServletReques是一个接口,我们不可能去实现里面的每个方法,便可新建一个MyServlet子类,重写一些自己调用的方法,具体实现逻辑如下:
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Description:
*
* @author: pavelchen
* @createDate: 2022/3/3
*/
public class MyServletREq extends HttpServletRequestWrapper {
private byte[] body = {123, 34, 116, 101, 115, 116, 34, 58, 32, 34, 99, 115, 34, 125};
public MyServletREq(HttpServletRequest request) {
super(request);
}
@Override
public String getMethod() {
return "post";
}
@Override
public String getRequestURI() {
return "/engine/webhook";
}
public ServletInputStream getInputStream() throws FileNotFoundException {
return new ServletInputStream() {
private int offset = 0;
@Override
public boolean isFinished() {
return offset >= body.length;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
}
@Override
public int read() throws IOException {
if (offset >= body.length) {
return -1;
}
int n = body[offset] & 0xff;
offset++;
return n;
}
};
}
}
调用逻辑:
public void test() {
HttpServletRequest req = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
MyServletREq req1 = new MyServletREq(req);
webHookApi.enter(req1);
}
这样便可对该方法进行单元测试。