Search in sources :

Example 1 with ModuleReflectionUtil

use of com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil in project checkstyle by checkstyle.

the class PackageObjectFactoryTest method testGenerateThirdPartyNameToFullModuleNameWithException.

/**
 * This method is for testing the case of an exception caught inside
 * {@code PackageObjectFactory.generateThirdPartyNameToFullModuleName}, a private method used
 * to initialize private field {@code PackageObjectFactory.thirdPartyNameToFullModuleNames}.
 * Since the method and the field both are private, the {@link TestUtil} is required to ensure
 * that the field is changed. Also, the expected exception should be thrown from the static
 * method {@link ModuleReflectionUtil#getCheckstyleModules}, so {@link Mockito#mockStatic}
 * is required to mock this exception.
 *
 * @throws Exception when the code tested throws an exception
 */
@Test
public void testGenerateThirdPartyNameToFullModuleNameWithException() throws Exception {
    final String name = "String";
    final String packageName = "java.lang";
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final Set<String> packages = Collections.singleton(packageName);
    final PackageObjectFactory objectFactory = new PackageObjectFactory(packages, classLoader, TRY_IN_ALL_REGISTERED_PACKAGES);
    try (MockedStatic<ModuleReflectionUtil> utilities = mockStatic(ModuleReflectionUtil.class)) {
        utilities.when(() -> ModuleReflectionUtil.getCheckstyleModules(packages, classLoader)).thenThrow(new IOException("mock exception"));
        final String internalFieldName = "thirdPartyNameToFullModuleNames";
        final Map<String, String> nullMap = TestUtil.getInternalState(objectFactory, internalFieldName);
        assertWithMessage("Expected uninitialized field").that(nullMap).isNull();
        final Object instance = objectFactory.createModule(name);
        assertWithMessage("Expected empty string").that(instance).isEqualTo("");
        final Map<String, String> emptyMap = TestUtil.getInternalState(objectFactory, internalFieldName);
        assertWithMessage("Expected empty map").that(emptyMap).isEmpty();
    }
}
Also used : ModuleReflectionUtil(com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Aggregations

ModuleReflectionUtil (com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil)1 IOException (java.io.IOException)1 Test (org.junit.jupiter.api.Test)1