我有一个带有布尔方法的ApiUtility Java类,希望为此编写JUNIT。
我在试着像下面这样。
我的Java类是蓝色的。
public static boolean isPublished(ResourceResolver resourceResolver, String path) {
logger.info("Inside isPublished");
Resource resource = resourceResolver.getResource(path);
logger.info("Inside isPublished resource ===== "+ resource);
Resource jcrResource = resource.getChild(Constants.JCR_CONTENT_NODE);
if (jcrResource != null) {
return jcrResource.getValueMap().get(Constants.CQ_LAST_REPLICATION_ACTION, "").equalsIgnoreCase(Constants.ACTIVATE);
}
return false;
}
我正试着写我的JUNIT类,如下所示。但不能。
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.RepositoryException;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import com.google.gson.Gson;
import ai.test.core.TestUtils;
import ai.test.core.constants.Constants;
import ai.test.core.service.ContentFragmentService;
import ai.test.core.service.EntityRelationUpdateServiceImpl;
import ai.test.core.service.ServletResponse;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
@ExtendWith({AemContextExtension.class, MockitoExtension.class})
public class AgenciesCommunityNodeAmangerServletTest {
private static final Gson gson = new Gson();
@Rule
private final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);
@Mock
ContentFragmentService agenciesService;
@Mock
EntityRelationUpdateServiceImpl updateService;
@InjectMocks
private AgenciesCommunityNodeAmangerServlet agenciesCommunityNodeAmangerServlet = new AgenciesCommunityNodeAmangerServlet();
private final String COMMUNITY_PATH = "/content/dam/content-admin/global/communities/agency/test";
@BeforeEach
void setUp() throws RepositoryException, URISyntaxException {
MockitoAnnotations.initMocks(this);
context.resourceResolver();
String json = gson.toJson(TestUtils.getMockBRGCommunityModel("/content/dam/content-admin/global/communities/agency/test"));
context.request().setContent(json.getBytes());
}
@Test
void doPostUpdateRelationShouldReturn200() throws IOException, LoginException {
when(updateService.updateEntityData(context.request(), COMMUNITY_PATH, Constants.COMMUNITIES)).thenReturn(TestUtils.getExpectedServletResponse(ServletResponse.ServletResponseType.RES_200));
Map<String, Object> params = new HashMap<>();
params.put(Constants.PATH, COMMUNITY_PATH);
params.put(Constants.TYPE, Constants.VERIFY);
context.request().setParameterMap(params);
agenciesCommunityNodeAmangerServlet.doPost(context.request(), context.response());
Assert.assertEquals("Response code should match", 200, context.response().getStatus());
}
@Test
void doPostUpdateRelationShouldThrowExceptionReturn500() throws IOException, LoginException {
when(updateService.updateEntityData(context.request(), COMMUNITY_PATH, Constants.COMMUNITIES)).thenReturn(TestUtils.getExpectedServletResponse(ServletResponse.ServletResponseType.RES_500));
Map<String, Object> params = new HashMap<>();
params.put(Constants.PATH, COMMUNITY_PATH);
params.put(Constants.TYPE, Constants.VERIFY);
context.request().setParameterMap(params);
agenciesCommunityNodeAmangerServlet.doPost(context.request(), context.response());
Assert.assertEquals("Response code should match", 500, context.response().getStatus());
}
}
但我得到如下空指针异常。
java.lang.NullPointerException
at ai.marcel.contentadmin.core.util.ApiUtility.isPublished(ApiUtility.java:1128)
at ai.marcel.contentadmin.core.servlets.AgenciesCommunityNodeAmangerServletTest.doPostUpdateRelationShouldReturn200(AgenciesCommunityNodeAmangerServletTest.java:129)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:628)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:117)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:127)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
我的servlet JAVA类如下所示
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
String type = request.getParameter(Constants.TYPE) != null ? request.getParameter(Constants.TYPE) : "";
logger.info("type outside IF Statement !type.isEmpty() ======= " + type);
//AgenciesCommunityModel agenciesCommunityModel = gson.fromJson(request.getReader(),AgenciesCommunityModel.class);//coming value here
if (!type.isEmpty() && type.equals(Constants.VERIFY)) {
logger.info("type INSIDE IF Statement !type.isEmpty() ======= " + type);
boolean publishStatus = ApiUtility.isPublished(request.getResourceResolver(),request.getPathInfo());
logger.info("publishStatus INSIDE agenciesCommunity ======= " + publishStatus);
if (publishStatus == true) {
ApiUtility.verifyContentFromMDS(updateRelationService, request, response, Constants.COMMUNITIES);
}
}
因为我从来没有在JUNIT上工作过,谁能帮帮我吗?
我正在写一个JUNIt测试类,但是没有成功。
2条答案
按热度按时间mbyulnm01#
请同时提供资源模拟,看起来资源解析器返回null。
ix0qys7i2#
您永远不会到达被测方法,因为您的模拟设置不正确。
问题出在:
这是stub静态方法的错误方法。请参阅Mockito文档中的Mocking static methods了解正确的方法。
通常,Mockito会报告不正确的清除尝试,如:
您不会收到此消息,因为您在前一步遇到了NPE异常-您调用
isPublished
的真实的实现,NPE从其中抛出。NPE被抛出,因为您没有在
resourceResolver
上存根任何方法。