如何在AEM6.2中编写Java类的Junit测试用例

时间:2016-07-31 12:06:37

标签: junit cq5 aem

我需要为Java类编写JUnit测试用例,这些Java类用于业务逻辑并与AEM交互。我没有找到编写JUnit测试用例的正确文档。如果您有任何此类文档,请求您与我分享。

2 个答案:

答案 0 :(得分:0)

不确定你在这里寻找什么。 AEM类的Junit测试用例与您编写的任何Java类没有什么不同。如果需要,您可能需要一个模拟框架来模拟Sling对象。

关于OSGI和吊索类的模拟的详细信息在apache吊索网站here上进行了描述,示例代码位于here

示例WCMUsePojo类 -

public class DisplayAsDataSourceWcmUse extends WCMUsePojo {


    /**
     * Display as script regex.
     */
    private static final String DISPLAY_AS_REGEX_EXPR = "^displayAs\\_(.*)\\.html$";

    /**
     * Datasource to the display listing.
     */
    private DataSource dataSource;

    /**
     * activate method.
     *
     * @throws Exception
     */
    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
    @Override
    public final void activate() throws Exception {
        this.buildDisplayAsOptions();
    }

    /**
     * Build the list of views for the DisplayAs Option.
     */
    private void buildDisplayAsOptions() {
        final SlingHttpServletRequest request = getRequest();
        final Resource componentResource = getCurrentComponent();
        List<Resource> resourceList = Collections.emptyList();

        if (null != componentResource) {
            final Iterable<Resource> children = () -> componentResource.listChildren();
            final Stream<Resource> childResourceStream = StreamSupport.stream(children.spliterator(), false);

            resourceList = childResourceStream
                    .filter(resource -> resource
                            .getName().matches(DISPLAY_AS_REGEX_EXPR))
                    .map(this::getMappedResource)
                    .collect(Collectors.toList());
            childResourceStream.close();
        }

        if (resourceList.isEmpty()) {
            dataSource = EmptyDataSource.instance();
        } else {
            dataSource = new SimpleDataSource(resourceList.iterator());
        }

        // place it in request for consumption by datasource mechanism
        request.setAttribute(DataSource.class.getName(), dataSource);

    }

    /**
     * Get resource instance of current component i.e. resource with path to component under apps/.
     *
     * @return component resource.
     */
    private Resource getCurrentComponent() {
        final Resource listResource = getResourceResolver().getResource((String) getRequest().getAttribute(Value
                .CONTENTPATH_ATTRIBUTE));
        if (listResource != null) {
            return getResourceResolver().getResource(listResource.getResourceType());
        }
        return null;
    }

    /**
     * Get Mapped Synthetic resource corresponding to the Display View.
     *
     * @param resource - Resource instance of display script.
     * @return ValueMapResource transformation of display script.
     */
    @SuppressWarnings("unused")
    private ValueMapResource getMappedResource(final Resource resource) {
        final String value = resource.getName().replaceFirst(DISPLAY_AS_REGEX_EXPR, "$1");

        // see if there's a better label
        final String text = ResourceUtil.getValueMap(resource).get(JcrConstants.JCR_TITLE, value);

        // create a ValueMap
        final Map<String, Object> map = new HashMap();
        map.put("text", text);
        map.put("value", value);

        // return a synthetic resource
        return new ValueMapResource(getResourceResolver(), new ResourceMetadata(), "", new ValueMapDecorator(map));

    }

    /**
     * Getter for dataSource.
     *
     * @return Datasource.
     */
    public final DataSource getDataSource() {
        return dataSource;
    }
}

使用Mockito进行单元测试的一种可能方法(不是非常理想的方式,因为你最终编写了很多模拟,在这种情况下,集成测试最适合) -

@RunWith(MockitoJUnitRunner.class)
public class DisplayAsDataSourceWcmUseTest {

    @Mock
    private Bindings bindings;
    @Mock
    private Resource currentResource;
    @Mock
    private Resource componentResource;
    @Mock
    private ResourceResolver resourceResolver;
    @Mock
    private SlingHttpServletRequest request;
    @Mock
    private Iterator<Resource> childItr;
    @Mock
    private Resource displayAsOne;
    @Mock
    private Resource displayAsTwo;

    @InjectMocks
    private DisplayAsDataSourceWcmUse displayAsDataSourceWcmUse;

    @Before
    public void setup() {

        when(bindings.get("resource")).thenReturn(currentResource);
        when(bindings.get("request")).thenReturn(request);
        when(request.getResourceResolver()).thenReturn(resourceResolver);
        when(request.getAttribute(Value.CONTENTPATH_ATTRIBUTE)).thenReturn("list/component/instance");

        when(currentResource.getResourceType()).thenReturn("current/resource/type");
        when(resourceResolver.getResource("current/resource/type")).thenReturn(componentResource);
        when(resourceResolver.getResource("list/component/instance")).thenReturn(currentResource);

        List<Resource> childRes = new ArrayList<>();
        childRes.add(displayAsOne);
        childRes.add(displayAsTwo);

        when(componentResource.listChildren()).thenReturn(childRes.iterator());
        when(displayAsOne.getName()).thenReturn("displayAs_One.html");
        when(displayAsTwo.getName()).thenReturn("displayAs_Two.html");

        Map<String, Object> vm1 = new HashMap();
        vm1.put(JcrConstants.JCR_TITLE, "Display Type One");

        when(displayAsOne.getValueMap()).thenReturn(new ValueMapDecorator(vm1));
        when(displayAsTwo.getValueMap()).thenReturn(new ValueMapDecorator(new HashMap()));

    }

    @Test
    public void test_display_option_are_set() throws Exception{
        displayAsDataSourceWcmUse = new DisplayAsDataSourceWcmUse();
        displayAsDataSourceWcmUse.init(bindings);

        assertTrue(displayAsDataSourceWcmUse.getDataSource() instanceof SimpleDataSource);
    }

    @Test
    public void test_empty_datasource_is_set() throws Exception{

        List<Resource> childRes = new ArrayList<>();
        when(componentResource.listChildren()).thenReturn(childRes.iterator());

        displayAsDataSourceWcmUse = new DisplayAsDataSourceWcmUse();
        displayAsDataSourceWcmUse.init(bindings);

        assertTrue(displayAsDataSourceWcmUse.getDataSource() instanceof EmptyDataSource);
    }

}

答案 1 :(得分:0)

看看 'ContiPerf 2'

ContiPerf是一个轻量级测试实用程序,使用户可以轻松利用JUnit 4测试用例作为性能测试,例如:用于连续性能测试。它的灵感来自JUnit 4的带注释的简单测试配置,以及JUnitPerf为性能测试包装单元测试的想法,但更强大,更易于使用:

  • 使用Java注释定义测试执行特性和性能要求。
  • 您可以将测试标记为运行一定次数或重复执行一段时间。
  • 性能要求可以是最大,平均,中等或任何百分位的时间。
  • 完美控制和性能要求的可读性您可以在两种不同模式下运行测试,将它们用作简单的单元测试或性能测试。
  • 与Eclipse和Maven轻松集成。
  • 将执行摘要导出为CSV文件。
  • 没有外部依赖的小型库(仅限JUnit)。
  • 使用自定义统计评估和跟踪机制轻松扩展。