Showing posts with label Junit. Show all posts
Showing posts with label Junit. Show all posts

Wednesday, November 6, 2024

Junit parallel execution Setup in pom.xml

 In maven based Java project, if your project has hundreds of Junit test cases it may take long time to run the application code build. To speed up build execution, it is recommended to setup your project to execute Junit Test in multi threaded parallel fashion. Below is sample code which you can put in your java module's pom.xml file:

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<configuration>

    <parallel>All</parallel>

    <forkCount>2C</forkCount>

    <reuseForks>true</reuseForks>

    <useSystemClassLoader>false</useSystemClassLoader>

</configuration>

</plugin>


Refer official documentation link for more details.

Tuesday, November 5, 2024

Junit Mocking Guide

 1. Mock private member of a class

Example to mock a private member "treeTypeProvider" of class CustomProvider.java

@InjectMocks
CustomProvider provider;

Field privateField = CustomProvider.class.getDeclaredField("treeTypeProvider");

privateField.setAccessible(true);

privateField.set(provider, treeTypeProvider);


2. Mock private method of a class

Ideally, you should avoid mocking a private method and coverage should be achieved through the public method that uses the particular private method. 

Example to mock a private method "getTypeProvider" of class CustomProvider.java

Class<?>[] params = new Class<?>[]{ParameterOne.class, ParameterTwo.class};

Field privateMethod = CustomProvider.class.getDeclaredMethod("getTypeProvider", params);

privateMethod.setAccessible(true);

privateMethod.invoke(provider, parameterOne, parameterTwo);


3. Mocking a Static class


Make sure you mock a Static class with a try-with-resources. Not doing so will affect Junit execution of other related classes using this Static class somewhere else in other Junit class.


try (MockedStatic<SampleUtils> utils = Mockito.mockStatic(SampleUtils.class)) {

utils.when(() -> SampleUtils.testMethod(node)).thenReturn(mockedNode);

......
......
 

}

4. Mocking object construction

Example to mock a construction statement like:

DocsProcessor processor = new DocsProcessor(); 

Mock it like below:

try (MockedConstruction< DocsProcessor > processor = Mockito.mockConstruction(DocsProcessor.class)) {

// Call any method that calls the DocsProcessor class constructor

......
......

        // Verify that constructor was called once 

        assertEquals(1, processor.constructed().size());

}

CDN | Clearing Cloudflare cache

In order to clear Cloudflare cache automatically via code, follow below steps: 1. Develop Custom TransportHandler Develop a custom Trans...