嘗試使用aem-mocks框架編寫一些適當的AEM集成測試。我們的目標是通過調用它的路徑來嘗試和測試一個servlet,例如:aem-mocks屬性測試servlet
E.g.一個AEM servlet
@SlingServlet(
paths = {"/bin/utils/emailSignUp"},
methods = {"POST"},
selectors = {"form"}
)
public class EmailSignUpFormServlet extends SlingAllMethodsServlet {
@Reference
SubmissionAgent submissionAgent;
@Reference
XSSFilter xssFilter;
public EmailSignUpFormServlet(){
}
public EmailSignUpFormServlet(SubmissionAgent submissionAgent, XSSFilter xssFilter) {
this.submissionAgent = submissionAgent;
this.xssFilter = xssFilter;
}
@Override
public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
String email = request.getParameter("email");
submissionAgent.saveForm(xssFilter.filter(email));
}
}
這裏是相應的測試,嘗試和做集成測試。注意我是如何調用servlet的「doPost」方法的,而不是通過某些API「POST」。
public class EmailSignUpFormServletTest {
@Rule
public final AemContext context = new AemContext();
@Mock
SubmissionAgent submissionAgent;
@Mock
XSSFilter xssFilter;
private EmailSignUpFormServlet emailSignUpFormServlet;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
Map<String,String> report = new HashMap<>();
report.put("statusCode","302");
when(submissionAgent.saveForm(any(String.class)).thenReturn(report);
}
@Test
public void emailSignUpFormDoesNotRequireRecaptchaChallenge() throws IOException {
// Setup test email value
context.request().setQueryString("[email protected]");
//===================================================================
/*
* WHAT I END UP DOING:
*/
// instantiate a new class of the servlet
emailSignUpFormServlet = new EmailSignUpFormServlet(submissionAgent, xssFilter);
// call the post method (Simulate the POST call)
emailSignUpFormServlet.doPost(context.request(),context.response());
/*
* WHAT I WOULD LIKE TO DO:
*/
// send request using some API that allows me to do post to the framework
// Example:
// context.request().POST("/bin/utils/emailSignUp") <--- doesn't exist!
//===================================================================
// assert response is internally redirected, hence expected status is a 302
assertEquals(302,context.response().getStatus());
}
}
我已經做了關於如何可以這樣做(here)和(here)了大量的研究,而這些鏈接顯示了很多關於如何設置爲context.request()對象的各種參數。但是,他們只是沒有說明如何最終執行'post'調用。