diff --git a/components/org.wso2.carbon.identity.scim2.common/pom.xml b/components/org.wso2.carbon.identity.scim2.common/pom.xml index 6c6a15738..b30448a5d 100644 --- a/components/org.wso2.carbon.identity.scim2.common/pom.xml +++ b/components/org.wso2.carbon.identity.scim2.common/pom.xml @@ -173,12 +173,14 @@ testng - org.powermock - powermock-module-testng + org.mockito + mockito-core + test - org.powermock - powermock-api-mockito2 + org.mockito + mockito-testng + test org.jacoco diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java index 8bf0f8c25..be61bc7a6 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java @@ -21,22 +21,26 @@ import org.apache.commons.lang.StringUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.scim2.common.DAO.GroupDAO; import org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.charon3.core.objects.Group; +import org.wso2.charon3.core.utils.AttributeUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.SimpleDateFormat; +import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -44,25 +48,21 @@ import java.util.Set; import java.util.HashSet; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.anyMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.AssertJUnit.assertTrue; -@PrepareForTest({IdentityDatabaseUtil.class, StringUtils.class, SCIMCommonUtils.class, SCIMGroupHandler.class, - IdentityTenantUtil.class}) -@PowerMockIgnore("java.sql.*") -public class SCIMGroupHandlerTest extends PowerMockTestCase { +public class SCIMGroupHandlerTest { @Mock private GroupDAO mockedGroupDAO; @@ -73,16 +73,32 @@ public class SCIMGroupHandlerTest extends PowerMockTestCase { @Mock private PreparedStatement mockedPreparedStatement; + private MockedStatic scimCommonUtils; + private MockedStatic identityDatabaseUtil; + private MockedStatic identityTenantUtil; + private MockedStatic stringUtils; + @BeforeMethod public void setUp() throws Exception { initMocks(this); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + stringUtils = mockStatic(StringUtils.class); + } + + @AfterMethod + public void tearDown() throws Exception { + scimCommonUtils.close(); + identityDatabaseUtil.close(); + identityTenantUtil.close(); + stringUtils.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @Test public void testAddMandatoryAttributes() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(SCIMCommonUtils.class); - mockStatic(IdentityDatabaseUtil.class); when(SCIMCommonUtils.getSCIMGroupURL(anyString())).thenReturn("ID"); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); @@ -110,8 +126,6 @@ public void testGetGroupAttributesById() throws Exception { @Test public void testCreateSCIMAttributes() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); Group group = new Group(); Date date = new Date(); @@ -132,8 +146,6 @@ public void testCreateSCIMAttributes() throws Exception { @Test public void testCreateSCIMAttributesExceptions() throws Exception { - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); ResultSet resultSet = mock(ResultSet.class); Group group = new Group(); @@ -147,22 +159,26 @@ public void testCreateSCIMAttributesExceptions() throws Exception { when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); when(mockedPreparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.next()).thenReturn(true); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.isExistingGroup(SCIMCommonUtils.getGroupNameWithDomain("ALREADY_EXISTANT_GROUP_NAME"), 1)).thenReturn(false); - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); - scimGroupHandler.createSCIMAttributes(group); - verify(mockedGroupDAO).addSCIMGroupAttributes(anyInt(), argumentCaptor.capture(), anyMap()); - assertEquals("testDisplayName", argumentCaptor.getValue()); + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(SCIMCommonUtils.getGroupNameWithDomain("ALREADY_EXISTANT_GROUP_NAME"), 1)) + .thenReturn(false); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + scimGroupHandler.createSCIMAttributes(group); + verify(mockedConstruction.constructed().get(0)) + .addSCIMGroupAttributes(anyInt(), argumentCaptor.capture(), anyMap()); + assertEquals("testDisplayName", argumentCaptor.getValue()); + } } @Test public void testGetGroupName() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(StringUtils.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); @@ -185,9 +201,6 @@ public void testGetGroupId() throws Exception { public void testGetGroupWithAttributes() throws Exception { Group group = new Group(); ResultSet resultSet = mock(ResultSet.class); - mockStatic(SCIMCommonUtils.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(StringUtils.class); Date date = new Date(2017, 10, 10, 10, 10, 10); Map attributes = new HashMap(); @@ -208,9 +221,6 @@ public void testGetGroupWithAttributes() throws Exception { public void testGetGroupWithAttributesSecondScenario() throws Exception { Group group = new Group(); ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(SCIMCommonUtils.class); Date today = Calendar.getInstance().getTime(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); @@ -226,18 +236,28 @@ public void testGetGroupWithAttributesSecondScenario() throws Exception { when(resultSet.next()).thenReturn(true); when(mockedPreparedStatement.executeQuery()).thenReturn(resultSet); when(mockedGroupDAO.isExistingGroup("EXISTING_GROUP_NAME", 1)).thenReturn(true); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); when(IdentityTenantUtil.getTenantDomain(1)).thenReturn("TENANT_DOMAIN"); when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/t/TENANT_DOMAIN/Groups"); - assertEquals(new SCIMGroupHandler(1).getGroupWithAttributes(group, "EXISTING_GROUP_NAME"), group); + + Instant mockInstant = Instant.now(); + try (MockedStatic mockedAttributeUtil = Mockito.mockStatic(AttributeUtil.class)) { + mockedAttributeUtil.when(() -> AttributeUtil.parseDateTime(anyString())).thenReturn(mockInstant); + + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + assertEquals(scimGroupHandler.getGroupWithAttributes(group, "EXISTING_GROUP_NAME"), group); + } + } } @Test public void testIsGroupExisting() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); @@ -254,61 +274,66 @@ public void testIsGroupExisting() throws Exception { @Test public void testDeleteGroupAttributes() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); - when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); when(mockedPreparedStatement.executeQuery()).thenReturn(resultSet); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); when(resultSet.next()).thenReturn(true); - when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); - - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); - scimGroupHandler.deleteGroupAttributes("GROUP_DELETABLE"); - verify(mockedGroupDAO).removeSCIMGroup(anyInt(), argumentCaptor.capture()); - assertEquals(argumentCaptor.getValue(),"GROUP_DELETABLE"); + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())).thenReturn(true); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + scimGroupHandler.deleteGroupAttributes("GROUP_DELETABLE"); + verify(mockedConstruction.constructed().get(0)).removeSCIMGroup(anyInt(), argumentCaptor.capture()); + assertEquals(argumentCaptor.getValue(), "GROUP_DELETABLE"); + } } @Test public void testUpdateRoleName() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); - scimGroupHandler.updateRoleName("EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); - verify(mockedGroupDAO).updateRoleName(anyInt(),argumentCaptor.capture(),anyString()); - assertEquals(argumentCaptor.getValue(),"EXISTENT_ROLE_NAME"); + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())).thenReturn(true); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + scimGroupHandler.updateRoleName("EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); + verify(mockedConstruction.constructed().get(0)).updateRoleName(anyInt(), argumentCaptor.capture(), anyString()); + assertEquals(argumentCaptor.getValue(), "EXISTENT_ROLE_NAME"); + } } @Test(expectedExceptions = IdentitySCIMException.class) public void testUpdateRoleNameNonExistent() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.isExistingGroup("NON_EXISTENT_ROLE_NAME", 1)).thenReturn(false); - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - scimGroupHandler.updateRoleName("NON_EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); - // This method is to test the throwing of an IdentitySCIMException, hence no assertion. + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup("NON_EXISTENT_ROLE_NAME", 1)).thenReturn(false); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + scimGroupHandler.updateRoleName("NON_EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); + } } @Test public void testListSCIMRoles() throws Exception { Set groups = mock(HashSet.class); ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java index 6150cf4bd..fa52abbc4 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java @@ -19,7 +19,6 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.apache.http.HttpStatus; -import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.identity.scim2.common.extenstion.SCIMUserStoreException; @@ -31,7 +30,7 @@ /** * Contains the unit test cases for DefaultSCIMUserStoreErrorResolver. */ -public class DefaultSCIMUserStoreErrorResolverTest extends PowerMockTestCase { +public class DefaultSCIMUserStoreErrorResolverTest { @Test public void testGetOrder() { diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java index 811f75bfc..4d2d23921 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java @@ -19,8 +19,9 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; + +import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -33,17 +34,16 @@ import java.util.HashMap; import java.util.Map; -import static org.mockito.Matchers.anyString; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertEquals; +import static org.mockito.Mockito.mockStatic; /** * Contains the unit test cases for IdentityResourceURLBuilder. */ -@PrepareForTest({IdentityTenantUtil.class, ServiceURLBuilder.class}) -public class IdentityResourceURLBuilderTest extends PowerMockTestCase { +public class IdentityResourceURLBuilderTest { private static final Map DUMMY_ENDPOINT_URI_MAP = new HashMap() {{ put("Users", "https://localhost:9444/scim2/Users"); @@ -56,14 +56,23 @@ public class IdentityResourceURLBuilderTest extends PowerMockTestCase { @Mock ServiceURL mockServiceUrl; + private MockedStatic serviceURLBuilder; + private MockedStatic identityTenantUtil; + @BeforeMethod public void setUpMethod() { initMocks(this); - mockStatic(ServiceURLBuilder.class); - when(ServiceURLBuilder.create()).thenReturn(mockServiceURLBuilder); + serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + serviceURLBuilder.when(() -> ServiceURLBuilder.create()).thenReturn(mockServiceURLBuilder); when(mockServiceURLBuilder.addPath(anyString())).thenReturn(mockServiceURLBuilder); - mockStatic(IdentityTenantUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + } + + @AfterMethod + public void tearDownMethod() { + serviceURLBuilder.close(); + identityTenantUtil.close(); } @DataProvider(name = "dataProviderForBuild") @@ -82,7 +91,7 @@ public Object[][] dataProviderForBuild() { public void testBuild(boolean isTenantQualifiedUrlsEnabled, String url, String resource, boolean throwError, String expected) throws NotFoundException, URLBuilderException { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); when(mockServiceURLBuilder.build()).thenAnswer(invocationOnMock -> { if (throwError) { throw new URLBuilderException("Protocol of service URL is not available."); @@ -109,7 +118,7 @@ public Object[][] dataProviderForBuildThrowingNotFoundException() { public void testBuildThrowingNotFoundException(boolean isTenantQualifiedUrlsEnabled, String resource) throws URLBuilderException, NotFoundException { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); when(mockServiceURLBuilder.build()).thenThrow( new URLBuilderException("Protocol of service URL is not available.")); IdentityResourceURLBuilder identityResourceURLBuilder = new IdentityResourceURLBuilder(); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java index d3011bddc..ff6d4118e 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java @@ -19,44 +19,43 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; +import org.mockito.MockedStatic; +import org.mockito.quality.Strictness; +import org.mockito.testng.MockitoSettings; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.testng.annotations.Listeners; +import org.mockito.testng.MockitoTestNGListener; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.identity.scim2.common.test.utils.CommonTestUtils; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.carbon.identity.scim2.common.utils.SCIMConfigProcessor; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.claim.ClaimManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; -import org.wso2.charon3.core.config.CharonConfiguration; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.extensions.UserManager; import java.nio.file.Paths; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.fail; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.anyInt; /** * Contains the unit test cases for IdentitySCIMManager. */ -@PrepareForTest({SCIMCommonUtils.class, PrivilegedCarbonContext.class, SCIMCommonComponentHolder.class,CharonConfiguration.class}) -@PowerMockIgnore({"javax.xml.*","org.w3c.dom.*","org.xml.sax.*"}) -public class IdentitySCIMManagerTest extends PowerMockTestCase { +@Listeners(MockitoTestNGListener.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class IdentitySCIMManagerTest { @Mock RealmService realmService; @@ -76,14 +75,16 @@ public class IdentitySCIMManagerTest extends PowerMockTestCase { private SCIMConfigProcessor scimConfigProcessor; private IdentitySCIMManager identitySCIMManager; + private MockedStatic scimCommonUtils; + private MockedStatic scimCommonComponentHolder; + @BeforeMethod public void setUp() throws Exception { + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); - - mockStatic(SCIMCommonComponentHolder.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); scimConfigProcessor = SCIMConfigProcessor.getInstance(); String filePath = Paths @@ -91,8 +92,6 @@ public void setUp() throws Exception { scimConfigProcessor.buildConfigFromFile(filePath); identitySCIMManager = IdentitySCIMManager.getInstance(); - mockStatic(SCIMCommonComponentHolder.class); - when(realmService.getTenantManager()).thenReturn(mockedTenantManager); when(mockedTenantManager.getTenantId(anyString())).thenReturn(-1234); when(realmService.getTenantUserRealm(anyInt())).thenReturn(mockedUserRealm); @@ -102,10 +101,11 @@ public void setUp() throws Exception { CommonTestUtils.initPrivilegedCarbonContext(); } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); + @AfterMethod + public void tearDown() { + scimCommonComponentHolder.close(); + scimCommonUtils.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @Test diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java index 8ac8b3e76..5c0954b7e 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java @@ -20,8 +20,9 @@ import org.apache.commons.lang.StringUtils; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; @@ -63,17 +64,17 @@ import java.util.HashSet; import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyListOf; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.doNothing; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertThrows; import static org.testng.Assert.assertTrue; @@ -87,8 +88,7 @@ /** * Contains the unit test cases for SCIMRoleManager. */ -@PrepareForTest({SCIMCommonUtils.class, OrganizationManagementUtil.class}) -public class SCIMRoleManagerTest extends PowerMockTestCase { +public class SCIMRoleManagerTest { private static final String SAMPLE_TENANT_DOMAIN = "carbon.super"; private static final String SAMPLE_TENANT_DOMAIN2 = "abc.com"; @@ -121,6 +121,9 @@ public class SCIMRoleManagerTest extends PowerMockTestCase { @Mock RoleManagementService mockRoleManagementService; + private MockedStatic scimCommonUtils; + private MockedStatic organizationManagementUtil; + @BeforeClass public void setUpClass() { @@ -129,13 +132,20 @@ public void setUpClass() { @BeforeMethod public void setUpMethod() { - - mockStatic(SCIMCommonUtils.class); - mockStatic(OrganizationManagementUtil.class); + MockitoAnnotations.openMocks(this); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + organizationManagementUtil = mockStatic(OrganizationManagementUtil.class); when(SCIMCommonUtils.getSCIMRoleURL(nullable(String.class))).thenReturn(DUMMY_SCIM_URL); when(mockRoleManagementService.getSystemRoles()).thenReturn(SYSTEM_ROLES); } + @AfterMethod + public void tearDownMethod() { + + scimCommonUtils.close(); + organizationManagementUtil.close(); + } + @DataProvider(name = "dataProviderForCreateRoleExistingRole") public Object[][] dataProviderForCreateRoleExistingRole() { @@ -163,8 +173,8 @@ public void testCreateRoleAddRoleExistingRoleName() OrganizationManagementException { Role role = getDummyRole(SAMPLE_VALID_ROLE_ID2, SAMPLE_EXISTING_ROLE_NAME); - when(mockRoleManagementService.addRole(anyString(), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())).thenThrow( + when(mockRoleManagementService.addRole(anyString(), anyList(), anyList(), + anyList(), anyString())).thenThrow( new IdentityRoleManagementException(ROLE_ALREADY_EXISTS.getCode(), "Role already exist for the role name: " + SAMPLE_EXISTING_ROLE_NAME)); when(OrganizationManagementUtil.isOrganization(anyString())).thenReturn(false); @@ -179,8 +189,8 @@ public void testCreateRoleAddRoleInvalidRoleName() Role role = getDummyRole(SAMPLE_VALID_ROLE_ID, SAMPLE_INVALID_ROLE_NAME); - when(mockRoleManagementService.addRole(anyString(), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())). + when(mockRoleManagementService.addRole(anyString(), anyList(), anyList(), + anyList(), anyString())). thenThrow(new IdentityRoleManagementClientException(INVALID_REQUEST.getCode(), String.format("Invalid role name: %s. Role names with the prefix: %s, is not allowed" + " to be created from externally in the system.", SAMPLE_INVALID_ROLE_NAME, @@ -206,8 +216,8 @@ public void testCreateRoleUnexpectedServerError(String roleId, String roleDispla OrganizationManagementException { Role role = getDummyRole(roleId, roleDisplayName); - when(mockRoleManagementService.addRole(anyString(), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())). + when(mockRoleManagementService.addRole(anyString(), anyList(), anyList(), + anyList(), anyString())). thenThrow(unExpectedErrorThrower(tenantDomain, sError, "Error while creating the role: %s in the tenantDomain: %s", roleDisplayName)); when(OrganizationManagementUtil.isOrganization(anyString())).thenReturn(false); @@ -235,8 +245,8 @@ public void testCreateRolePositive(String roleId, String roleDisplayName, String OrganizationManagementException { Role role = getDummyRole(roleId, roleDisplayName); - when(mockRoleManagementService.addRole(nullable(String.class), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(new RoleBasicInfo(roleId, roleDisplayName)); + when(mockRoleManagementService.addRole(nullable(String.class), anyList(), anyList(), + anyList(), anyString())).thenReturn(new RoleBasicInfo(roleId, roleDisplayName)); when(OrganizationManagementUtil.isOrganization(anyString())).thenReturn(false); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); Role createdRole = scimRoleManager.createRole(role); @@ -633,10 +643,10 @@ public void testUpdateRoleUpdateRoleName(String roleId, String oldRoleName, Stri Role[] oldAndNewRoles = getOldAndNewRoleDummies(roleId, oldRoleName, newRoleName, type); when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.updateUserListOfRole( - eq(roleId), anyListOf(String.class), anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.setPermissionsForRole(eq(roleId), anyListOf(String.class), anyString())). + eq(roleId), anyList(), anyList(), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.setPermissionsForRole(eq(roleId), anyList(), anyString())). thenReturn(roleBasicInfo); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); @@ -725,7 +735,7 @@ public void testUpdateRoleUpdateUserListOfRoleThrowingErrors(String roleId, Stri when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.updateUserListOfRole( - anyString(), anyListOf(String.class), anyListOf(String.class), anyString())). + anyString(), anyList(), anyList(), anyString())). thenAnswer(invocationOnMock -> { String roleIdArg = invocationOnMock.getArgument(0); String tenantDomainArg = invocationOnMock.getArgument(3); @@ -770,7 +780,7 @@ public void testUpdateRoleUpdateGroupListOfRoleThrowingErrors(String roleId, Str Role[] oldAndNewRoles = getOldAndNewRoleDummies(roleId, oldRoleName, newRoleName, type); when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.updateGroupListOfRole( - anyString(), anyListOf(String.class), anyListOf(String.class), anyString())). + anyString(), anyList(), anyList(), anyString())). thenAnswer(invocationOnMock -> { String roleIdArg = invocationOnMock.getArgument(0); String tenantDomainArg = invocationOnMock.getArgument(3); @@ -785,8 +795,8 @@ public void testUpdateRoleUpdateGroupListOfRoleThrowingErrors(String roleId, Str if (unExpectedErrors != null) throw unExpectedErrors; return roleBasicInfo; }); - when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); scimRoleManager.updateRole(oldAndNewRoles[0], oldAndNewRoles[1]); @@ -817,7 +827,7 @@ public void testRoleUpdatePermissionListOfRoleThrowingErrors(String roleId, Stri Role[] oldAndNewRoles = getOldAndNewRoleDummies(roleId, oldRoleName, newRoleName, permissionType); when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.setPermissionsForRole( - anyString(), anyListOf(String.class), anyString())). + anyString(), anyList(), anyString())). thenAnswer(invocationOnMock -> { String roleIdArg = invocationOnMock.getArgument(0); String tenantDomainArg = invocationOnMock.getArgument(2); @@ -838,10 +848,10 @@ public void testRoleUpdatePermissionListOfRoleThrowingErrors(String roleId, Stri if (unExpectedErrors != null) throw unExpectedErrors; return roleBasicInfo; }); - when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); scimRoleManager.updateRole(oldAndNewRoles[0], oldAndNewRoles[1]); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java index 96eca05c0..890de538f 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java @@ -19,13 +19,13 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.mockito.Mock; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.role.v2.mgt.core.RoleManagementService; import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementException; @@ -43,6 +43,7 @@ import java.util.List; import java.util.Map; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; @@ -50,8 +51,7 @@ /** * Contains the unit test cases for SCIMRoleManagerV2. */ -@PrepareForTest({IdentityUtil.class}) -public class SCIMRoleManagerV2Test extends PowerMockTestCase { +public class SCIMRoleManagerV2Test { private static final String SAMPLE_TENANT_DOMAIN = "carbon.super"; private static final String SAMPLE_VALID_ROLE_ID = "595f5508-f286-446a-86c4-5071e07b98fc"; @@ -64,6 +64,8 @@ public class SCIMRoleManagerV2Test extends PowerMockTestCase { private SCIMRoleManagerV2 scimRoleManagerV2; + private MockedStatic identityUtil; + @BeforeClass public void setUpClass() { @@ -73,10 +75,16 @@ public void setUpClass() { @BeforeMethod public void setUpMethod() { - PowerMockito.mockStatic(IdentityUtil.class); + identityUtil = mockStatic(IdentityUtil.class); scimRoleManagerV2 = new SCIMRoleManagerV2(roleManagementService, SAMPLE_TENANT_DOMAIN); } + @AfterMethod + public void tearDown() { + identityUtil.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); + } + @DataProvider(name = "scimOperations") public Object[][] provideScimOperations() { diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java index fa83a8447..e7e9241ce 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (https://www.wso2.org) * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -20,19 +20,17 @@ import org.apache.commons.lang.StringUtils; import org.mockito.Mock; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.api.support.membermodification.MemberModifier; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.common.model.InboundProvisioningConfig; import org.wso2.carbon.identity.application.common.model.ServiceProvider; @@ -48,6 +46,9 @@ import org.wso2.carbon.identity.scim2.common.extenstion.SCIMUserStoreErrorResolver; import org.wso2.carbon.identity.scim2.common.group.SCIMGroupHandler; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; +import org.wso2.carbon.user.core.UserStoreClientException; +import org.wso2.charon3.core.exceptions.NotImplementedException; +import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.objects.plainobjects.UsersGetResponse; import org.wso2.charon3.core.objects.plainobjects.GroupsGetResponse; import org.wso2.carbon.identity.scim2.common.test.utils.CommonTestUtils; @@ -85,11 +86,13 @@ import org.wso2.charon3.core.schema.SCIMDefinitions; import org.wso2.charon3.core.schema.SCIMResourceSchemaManager; import org.wso2.charon3.core.schema.SCIMResourceTypeSchema; +import org.wso2.charon3.core.utils.ResourceManagerUtil; import org.wso2.charon3.core.utils.codeutils.ExpressionNode; import org.wso2.charon3.core.utils.codeutils.FilterTreeManager; import org.wso2.charon3.core.utils.codeutils.Node; import org.wso2.charon3.core.utils.codeutils.SearchRequest; +import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -107,14 +110,8 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.doNothing; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; @@ -122,13 +119,7 @@ /* * Unit tests for SCIMUserManager */ -@PrepareForTest({SCIMGroupHandler.class, IdentityUtil.class, SCIMUserSchemaExtensionBuilder.class, - SCIMAttributeSchema.class, AttributeMapper.class, ClaimMetadataHandler.class, SCIMCommonUtils.class, - IdentityTenantUtil.class, AbstractUserStoreManager.class, Group.class, UserCoreUtil.class, - ApplicationManagementService.class, RolePermissionManagementService.class, SCIMCommonComponentHolder.class, - SCIMUserManager.class, CarbonConstants.class}) -@PowerMockIgnore({"java.sql.*","javax.xml.*","org.w3c.dom.*","org.xml.sax.*"}) -public class SCIMUserManagerTest extends PowerMockTestCase { +public class SCIMUserManagerTest { private static final String USERNAME_LOCAL_CLAIM = "http://wso2.org/claims/username"; private static final String USERID_LOCAL_CLAIM = "http://wso2.org/claims/userid"; @@ -195,12 +186,47 @@ public class SCIMUserManagerTest extends PowerMockTestCase { @Mock private RolePermissionManagementService mockedRolePermissionManagementService; - + private MockedStatic scimUserSchemaExtensionBuilder; + private MockedStatic identityUtil; + private MockedStatic scimCommonUtils; + private MockedStatic attributeMapper; + private MockedStatic claimMetadataHandler; + private MockedStatic carbonConstants; + private MockedStatic identityTenantUtil; + private MockedStatic applicationManagementServiceMockedStatic; + private MockedStatic scimCommonComponentHolder; + private MockedStatic resourceManagerUtil; + private MockedStatic userCoreUtil; @BeforeMethod - public void setUp() throws Exception { - + public void setUpMethod() { initMocks(this); + identityUtil = mockStatic(IdentityUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + carbonConstants = mockStatic(CarbonConstants.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + applicationManagementServiceMockedStatic = mockStatic(ApplicationManagementService.class); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + scimUserSchemaExtensionBuilder = mockStatic(SCIMUserSchemaExtensionBuilder.class); + claimMetadataHandler = mockStatic(ClaimMetadataHandler.class); + resourceManagerUtil = mockStatic(ResourceManagerUtil.class); + SCIMUserSchemaExtensionBuilder mockSCIMUserSchemaExtensionBuilder = mock(SCIMUserSchemaExtensionBuilder.class); + scimUserSchemaExtensionBuilder.when(SCIMUserSchemaExtensionBuilder::getInstance).thenReturn(mockSCIMUserSchemaExtensionBuilder); + when(mockSCIMUserSchemaExtensionBuilder.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); + } + + @AfterMethod + public void tearDown() { + identityUtil.close(); + scimCommonUtils.close(); + carbonConstants.close(); + identityTenantUtil.close(); + applicationManagementServiceMockedStatic.close(); + scimCommonComponentHolder.close(); + scimUserSchemaExtensionBuilder.close(); + claimMetadataHandler.close(); + resourceManagerUtil.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @DataProvider(name = "ClaimData") @@ -265,28 +291,26 @@ public void testGetMe(Object[] cMap, HashMap required, String[] when(mockedClaimManager.getAllClaimMappings(anyString())).thenReturn((ClaimMapping[]) cMap); SCIMUserSchemaExtensionBuilder sb = spy(new SCIMUserSchemaExtensionBuilder()); - mockStatic(SCIMUserSchemaExtensionBuilder.class); - when(SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); + scimUserSchemaExtensionBuilder.when(SCIMUserSchemaExtensionBuilder::getInstance).thenReturn(sb); when(sb.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); - mockStatic(IdentityUtil.class); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn("testPrimaryDomain"); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("testPrimaryDomain"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); - MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") - .set(mockedUserStoreManager, new HashMap()); + Field userStoreManagerHolderField = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); + userStoreManagerHolderField.setAccessible(true); + userStoreManagerHolderField.set(mockedUserStoreManager, new HashMap()); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())).thenReturn(secondaryUserStoreManager); when(mockedUserStoreManager.isSCIMEnabled()).thenReturn(true); when(mockedUserStoreManager.getRoleListOfUser(anyString())).thenReturn(userRoles); - mockStatic(AttributeMapper.class); - when(AttributeMapper.constructSCIMObjectFromAttributes(any(), anyMap(), anyInt())).thenReturn(mockedUser); + attributeMapper = mockStatic(AttributeMapper.class); + attributeMapper.when(() -> AttributeMapper.constructSCIMObjectFromAttributes(any(), anyMap(), anyInt())).thenReturn(mockedUser); when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockedRealmConfig); when(mockedRealmConfig.getEveryOneRoleName()).thenReturn("roleName"); when(mockedUserStoreManager.getTenantId()).thenReturn(1234567); @@ -294,31 +318,26 @@ public void testGetMe(Object[] cMap, HashMap required, String[] user.setUsername("testUserName"); user.setUserID(UUID.randomUUID().toString()); when(mockedUserStoreManager.getUser(anyString(), nullable(String.class))).thenReturn(user); - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); CommonTestUtils.initPrivilegedCarbonContext(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(ClaimMetadataHandler.class); - when(ClaimMetadataHandler.getInstance()).thenReturn(mockClaimMetadataHandler); + claimMetadataHandler.when(ClaimMetadataHandler::getInstance).thenReturn(mockClaimMetadataHandler); when(mockClaimMetadataHandler.getMappingsFromOtherDialectToCarbon(anyString(), anySet(), anyString())) .thenReturn(new HashSet()); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); assertNotNull(scimUserManager.getMe("testUserName", required)); + attributeMapper.close(); } @Test(dataProvider = "groupName") public void testGetGroup(String groupId, String roleName, String userStoreDomain, Object expected) throws Exception { - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.getGroupNameById(anyInt(), anyString())).thenReturn(roleName); - mockStatic(IdentityUtil.class); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); when(mockedUserStoreManager.getGroup(groupId, null)). thenReturn(buildUserCoreGroupResponse(roleName, groupId, userStoreDomain)); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); @@ -344,13 +363,13 @@ public Object[][] groupName() throws Exception { @Test(dataProvider = "getGroupException") public void testGetGroupWithExceptions(String roleName, String userStoreDomain) throws Exception { - MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") - .set(mockedUserStoreManager, new HashMap()); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + Field field = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); + field.setAccessible(true); + field.set(mockedUserStoreManager, new HashMap()); - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.getGroupNameById(anyInt(), anyString())).thenReturn(roleName); - mockStatic(IdentityUtil.class); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); try { @@ -397,18 +416,18 @@ public void testListGroupsWithFilter(String filter, String roleName, String user Map attributes = new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1"); }}; - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.getGroupNameList(anyString(), anyString(), anyInt(), anyString())) .thenReturn(list.toArray(new String[0])); - mockStatic(IdentityUtil.class); when(mockedGroupDAO.isExistingGroup("testRole", 0)).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(0, "testRole")).thenReturn(attributes); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); - MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") - .set(mockedUserStoreManager, new HashMap()); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + Field field = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); + field.setAccessible(true); + field.set(mockedUserStoreManager, new HashMap()); when(mockedUserStoreManager.isExistingRole(anyString(), anyBoolean())).thenReturn(true); when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockRealmConfig); @@ -422,7 +441,6 @@ public void testListGroupsWithFilter(String filter, String roleName, String user anyInt(), nullable(String.class), nullable(String.class))).thenReturn(Arrays.asList(groupsArray.clone())); when(mockedUserStoreManager.getGroupByGroupName(roleName, null)). thenReturn(buildUserCoreGroupResponse(roleName, "123456789", null)); - whenNew(RealmConfiguration.class).withAnyArguments().thenReturn(mockRealmConfig); when(mockRealmConfig.getAdminRoleName()).thenReturn("admin"); when(mockRealmConfig.isPrimary()).thenReturn(false); when(mockRealmConfig.getUserStoreProperty(anyString())).thenReturn("value"); @@ -430,14 +448,12 @@ public void testListGroupsWithFilter(String filter, String roleName, String user when(mockIdentityUtil.extractDomainFromName(anyString())).thenReturn("value"); - mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put("urn:ietf:params:scim:schemas:core:2.0:User:userName", "http://wso2.org/claims/username"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); GroupsGetResponse groupsResponse = scimUserManager.listGroupsWithGET(node, 1, 1, null, null, @@ -457,14 +473,11 @@ public void testListUsersWithGET(List use "http://wso2.org/claims/username"); scimToLocalClaimMap.put("urn:ietf:params:scim:schemas:core:2.0:id", "http://wso2.org/claims/userid"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); - when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); - when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/userid", "*", null)).thenReturn(users); when(mockedUserStoreManager.getRoleListOfUserWithID(anyString())).thenReturn(new ArrayList<>()); when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockedRealmConfig); @@ -475,9 +488,7 @@ public void testListUsersWithGET(List use when(mockedUserStoreManager.getSecondaryUserStoreManager("SECONDARY")).thenReturn(secondaryUserStoreManager); when(secondaryUserStoreManager.isSCIMEnabled()).thenReturn(isScimEnabledForSecondary); - mockStatic(IdentityTenantUtil.class); - - when(IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); + identityTenantUtil.when(() -> IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockedRealmConfig); HashMap requiredClaimsMap = new HashMap<>(); @@ -544,13 +555,12 @@ public void testFilteringUsersWithGET(List() {{ + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/userid", "*", null)).thenReturn(users); when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/givenname", "testUser", "default")) @@ -565,11 +575,9 @@ public void testFilteringUsersWithGET(List() {{ + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID(any(Condition.class), anyString(), anyString(), eq(count), anyInt(), nullable(String.class), nullable(String.class))).thenReturn(filteredUsersWithPagination); @@ -686,8 +693,7 @@ public void testFilteringUsersWithGETWithPagination(List IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockedRealmConfig); ClaimMapping[] claimMappings = getTestClaimMappings(); @@ -705,9 +711,9 @@ public void testFilteringUsersWithGETWithPagination(List SCIMCommonUtils.isConsiderTotalRecordsForTotalResultOfLDAPEnabled()) .thenReturn(isConsiderTotalRecordsForTotalResultOfLDAPEnabled); - when(SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) + scimCommonUtils.when(() -> SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) .thenReturn(isConsiderMaxLimitForTotalResultEnabled); Map supportedByDefaultProperties = new HashMap() {{ @@ -747,6 +753,7 @@ public void testFilteringUsersWithGETWithPagination(List require when(abstractUserStoreManager.getGroupByGroupName(role, null)). thenReturn(buildUserCoreGroupResponse(role, "123456789", null)); } - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); - mockStatic(UserCoreUtil.class); - when(UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - - SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); - GroupsGetResponse groupsResponse = scimUserManager - .listGroupsWithGET(null, 1, null, null, null, "Application", requiredAttributes); - - assertEquals(groupsResponse.getGroups().get(0).getDisplayName(), "Application/Apple"); - assertEquals(groupsResponse.getGroups().get(1).getDisplayName(), "Application/MyApp"); - assertEquals(groupsResponse.getGroups().size(), 2); + userCoreUtil = mockStatic(UserCoreUtil.class); + userCoreUtil.when(() -> UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); + + try (MockedConstruction mocked = mockConstruction(SCIMGroupHandler.class, + (mock, context) -> { + when(mock.listSCIMRoles()).thenReturn(new HashSet<>(Arrays.asList(roles))); + })) { + + CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("Application"); + SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); + GroupsGetResponse groupsResponse = scimUserManager + .listGroupsWithGET(null, 1, null, null, null, "Application", requiredAttributes); + + assertEquals(groupsResponse.getGroups().get(0).getDisplayName(), "Application/Apple"); + assertEquals(groupsResponse.getGroups().get(1).getDisplayName(), "Application/MyApp"); + assertEquals(groupsResponse.getGroups().size(), 2); + } + userCoreUtil.close(); } @DataProvider(name = "listApplicationRoles") @@ -1021,23 +1035,22 @@ public void testFilterApplicationRolesWithDomainParam(String filter, String[] ro when(abstractUserStoreManager.getGroupByGroupName(role, null)). thenReturn(buildUserCoreGroupResponse(role, "123456", "dummyDomain")); } - mockStatic(UserCoreUtil.class); - when(UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); + userCoreUtil = mockStatic(UserCoreUtil.class); + userCoreUtil.when(() -> UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; - + when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockedRealmConfig); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("Application"); SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); GroupsGetResponse groupsResponse = scimUserManager .listGroupsWithGET(node, 1, null, null, null, "Application", requiredAttributes); assertEquals(groupsResponse.getGroups().get(0).getDisplayName(), "Application/MyApp"); assertEquals(groupsResponse.getGroups().size(), 1); + userCoreUtil.close(); } @DataProvider(name = "applicationDomainWithFilters") @@ -1055,12 +1068,6 @@ public Object[][] applicationDomainWithFilters() { }; } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - @Test public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { @@ -1099,12 +1106,10 @@ public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(externalClaimMap); when(mockClaimMetadataManagementService.getLocalClaims(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) .thenReturn(localClaimMap); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(true); + scimCommonUtils.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(true); SCIMUserSchemaExtensionBuilder sb = spy(new SCIMUserSchemaExtensionBuilder()); - mockStatic(SCIMUserSchemaExtensionBuilder.class); - when(SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); + scimUserSchemaExtensionBuilder.when(() -> SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); when(sb.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); when(mockedSCIMAttributeSchema.getSubAttributeSchema(anyString())).thenReturn(mockedAttributeSchema); when(mockedAttributeSchema.getType()).thenReturn(SCIMDefinitions.DataType.STRING); @@ -1117,8 +1122,7 @@ public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { @Test public void testGetEnterpriseUserSchemaWhenDisabled() throws Exception { - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(false); + scimCommonUtils.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(false); SCIMUserManager userManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); assertEquals(userManager.getEnterpriseUserSchema(), null); @@ -1137,14 +1141,14 @@ public void testUpdateUserWithUsernameChange() throws Exception { newUser.setUserName("newUser"); newUser.setId("newUserId"); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); SCIMUserManager scimUserManager = spy(new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); + resourceManagerUtil.when(() -> ResourceManagerUtil.getAllAttributeURIs(Mockito.any())) + .thenReturn(new HashMap<>()); doReturn(oldUser).when(scimUserManager).getUser(anyString(), anyMap()); - mockStatic(IdentityUtil.class); when(IdentityUtil.isUserStoreInUsernameCaseSensitive(anyString())).thenReturn(true); boolean hasExpectedBehaviour = false; @@ -1198,7 +1202,6 @@ public void testGetGroupPermissions(String roleName, String[] permission, Object SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(SCIMCommonComponentHolder.class); when(SCIMCommonComponentHolder.getRolePermissionManagementService()) .thenReturn(mockedRolePermissionManagementService); when(mockedRolePermissionManagementService.getRolePermissions(eq(roleName), anyInt())).thenReturn(permission); @@ -1332,7 +1335,6 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma groupsMap.put("Internal/admin", group3); groupsMap.put("Internal/everyone", group4); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenCallRealMethod(); when(SCIMCommonUtils.mandateDomainForUsernamesAndGroupNamesInResponse()). @@ -1340,8 +1342,8 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(SCIMCommonUtils.prependDomain(anyString())).thenCallRealMethod(); when(SCIMCommonUtils.isHybridRole(anyString())).thenCallRealMethod(); - mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; + CommonTestUtils.initPrivilegedCarbonContext(); org.wso2.carbon.user.core.common.User user = mock(org.wso2.carbon.user.core.common.User.class); when(user.getUserStoreDomain()).thenReturn(userStoreDomainName); @@ -1349,7 +1351,7 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(user.getDomainQualifiedUsername()).thenReturn(domainQualifiedUserName); when(user.getUserID()).thenReturn((userId)); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), nullable(String[].class), anyString())).thenReturn(user); when(mockedUserStoreManager.getTenantId()).thenReturn(1234567); when(mockedUserStoreManager.getUserClaimValuesWithID(anyString(), any(), nullable(String.class))) @@ -1370,13 +1372,11 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(mockedRealmConfig.isPrimary()).thenReturn(true); when(mockedRealmConfig.getEveryOneRoleName()).thenReturn("Internal/everyone"); - PowerMockito.whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); doNothing().when(mockedGroupDAO).addSCIMGroupAttributesToSCIMDisabledHybridRoles(anyInt(), any()); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(IdentityUtil.class); when(IdentityUtil.isGroupsVsRolesSeparationImprovementsEnabled()) .thenReturn(isGroupsVsRolesSeparationImprovementsEnabled); when(IdentityUtil.getProperty(SCIMCommonConstants.PRIMARY_LOGIN_IDENTIFIER_CLAIM)) @@ -1384,7 +1384,6 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(IdentityUtil.getProperty(SCIMCommonConstants.ENABLE_LOGIN_IDENTIFIERS)).thenReturn(enableLoginIdentifiers); when(IdentityUtil.extractDomainFromName(anyString())).thenReturn("Internal"); - PowerMockito.whenNew(SCIMGroupHandler.class).withArguments(anyInt()).thenReturn(mockedSCIMGroupHandler); when(mockedSCIMGroupHandler.listSCIMRoles()).thenReturn(scimRoles); when(mockedSCIMGroupHandler.getGroupWithAttributes(any(Group.class), anyString())) .thenAnswer(new Answer() { @@ -1395,16 +1394,20 @@ public Group answer(InvocationOnMock invocation) throws Throwable { } }); - mockStatic(IdentityTenantUtil.class); - when(IdentityTenantUtil.getTenantId("carbon.super")).thenReturn(-1234); - User scimUser = scimUserManager.getUser(userId, requiredAttributes); - assertEquals(scimUser.getAttributeList().size(), expectedNoOfAttributes); - // Check whether the added multi valued attributes for the addresses attribute are contained. - assertEquals( - ((MultiValuedAttribute) scimUser.getAttribute("addresses")).getAttributeValues().size(), 2); - assertEquals(scimUser.getUserName(), expectedUserName); - assertEquals(scimUser.getGroups().size(), expectedNoOfGroups); - assertEquals(scimUser.getRoles().size(), expectedNoOfRoles); + try (MockedConstruction mocked = mockConstruction(SCIMGroupHandler.class, + (mock, context) -> { + when(mock.getGroupWithAttributes(any(),any())).thenReturn(group1); + })) { + when(IdentityTenantUtil.getTenantId("carbon.super")).thenReturn(-1234); + User scimUser = scimUserManager.getUser(userId, requiredAttributes); + assertEquals(scimUser.getAttributeList().size(), expectedNoOfAttributes); + // Check whether the added multi valued attributes for the addresses attribute are contained. + assertEquals( + ((MultiValuedAttribute) scimUser.getAttribute("addresses")).getAttributeValues().size(), 2); + assertEquals(scimUser.getUserName(), expectedUserName); + assertEquals(scimUser.getGroups().size(), expectedNoOfGroups); + assertEquals(scimUser.getRoles().size(), expectedNoOfRoles); + } } @DataProvider(name = "exceptionHandlingConfigurations") @@ -1424,7 +1427,6 @@ public void testGetUserWithInvalidUserID(Boolean isNotifyUserstoreStatusEnabled) Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, USERID_LOCAL_CLAIM); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); when(SCIMCommonUtils.isNotifyUserstoreStatusEnabled()).thenReturn(isNotifyUserstoreStatusEnabled); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, @@ -1434,7 +1436,6 @@ public void testGetUserWithInvalidUserID(Boolean isNotifyUserstoreStatusEnabled) List scimUserStoreErrorResolvers = new ArrayList<>(); SCIMUserStoreErrorResolver scimUserStoreErrorResolver = new DefaultSCIMUserStoreErrorResolver(); scimUserStoreErrorResolvers.add(scimUserStoreErrorResolver); - mockStatic(SCIMCommonComponentHolder.class); when(SCIMCommonComponentHolder.getScimUserStoreErrorResolverList()).thenReturn(scimUserStoreErrorResolvers); scimUserManager.getUser(userId, requiredAttributes); // This method is for testing of throwing CharonException, hence no assertion. @@ -1449,9 +1450,8 @@ public void testGetUserWhenSCIMisDisabled() throws Exception { Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, USERID_LOCAL_CLAIM); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); org.wso2.carbon.user.core.common.User user = mock(org.wso2.carbon.user.core.common.User.class); @@ -1485,13 +1485,11 @@ public void testDeleteUserWithInvalidUserId() throws Exception { scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "userIdURI"); List coreUsers = new ArrayList<>(); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID(anyString(), anyString(), anyString())).thenReturn(coreUsers); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); scimUserManager.deleteUser(userId); @@ -1509,15 +1507,13 @@ public void testDeleteUserWhenSCIMisDisabled() throws Exception { coreUser.setUsername("coreUser"); coreUser.setUserStoreDomain("DomainName"); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), any(), anyString())).thenReturn(coreUser); when(mockedUserStoreManager.getSecondaryUserStoreManager("DomainName")).thenReturn(mockedUserStoreManager); when(mockedUserStoreManager.isSCIMEnabled()).thenReturn(false); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); scimUserManager.deleteUser(userId); @@ -1534,9 +1530,8 @@ public void testDeleteUserWithUserStoreDomainMismatch() throws Exception { coreUser.setUsername("coreUser"); coreUser.setUserStoreDomain("PRIMARY"); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), any(), anyString())).thenReturn(coreUser); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -1544,7 +1539,6 @@ public void testDeleteUserWithUserStoreDomainMismatch() throws Exception { inboundProvisioningConfig.setProvisioningUserStore("SECONDARY"); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.setInboundProvisioningConfig(inboundProvisioningConfig); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(serviceProvider); scimUserManager.deleteUser(userId); @@ -1557,16 +1551,16 @@ public void testCreateUserWithInvalidUserStoreName() throws Exception { User user = new User(); user.setUserName("testUser"); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())) .thenReturn(null); InboundProvisioningConfig inboundProvisioningConfig = new InboundProvisioningConfig(); inboundProvisioningConfig.setProvisioningUserStore("DomainName"); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.setInboundProvisioningConfig(inboundProvisioningConfig); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(serviceProvider); + when(mockedUserStoreManager.isExistingUser(nullable(String.class))) + .thenThrow(new UserStoreException(new UserStoreClientException("TestException"))); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); scimUserManager.createUser(user, null); @@ -1579,7 +1573,6 @@ public void testCreateUserWhenSCIMisDisabled() throws Exception { User user = new User(); user.setUserName("testUser"); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())) .thenReturn(secondaryUserStoreManager); when(secondaryUserStoreManager.isSCIMEnabled()).thenReturn(false); @@ -1588,11 +1581,12 @@ public void testCreateUserWhenSCIMisDisabled() throws Exception { inboundProvisioningConfig.setProvisioningUserStore("DomainName"); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.setInboundProvisioningConfig(inboundProvisioningConfig); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(serviceProvider); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + doThrow(new NotImplementedException()).when(mockedUser).setSchemas(Mockito.any(UserManager.class)); + mockedUser.setSchemas(Mockito.mock(UserManager.class)); scimUserManager.createUser(user, null); // This method is for testing of throwing CharonException, hence no assertion. } @@ -1614,18 +1608,16 @@ public void testCreateUserWithExistingUserName(String isLoginIdentifiersEnabled) user.setUserName("DomainName/testUser1"); String[] existingUserList = {"user1", "user2"}; - mockStatic(IdentityUtil.class); when(IdentityUtil.getProperty(SCIMCommonConstants.PRIMARY_LOGIN_IDENTIFIER_CLAIM)) .thenReturn("primaryLoginIdentifierClaim"); when(IdentityUtil.getProperty(SCIMCommonConstants.ENABLE_LOGIN_IDENTIFIERS)) .thenReturn(isLoginIdentifiersEnabled); when(IdentityUtil.extractDomainFromName(anyString())).thenCallRealMethod(); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.isExistingUserWithID(anyString())).thenReturn(true); when(mockedUserStoreManager.isExistingUser(anyString())).thenReturn(true); when(mockedUserStoreManager.getUserList(anyString(), anyString(), nullable(String.class))).thenReturn(existingUserList); @@ -1648,21 +1640,18 @@ public void testCreateUserWithConflictingLoginIdentifier() throws Exception { Map scimToLocalClaimMappings = new HashMap<>(); scimToLocalClaimMappings.put(SCIMConstants.UserSchemaConstants.DISPLAY_NAME_URI, DISPLAY_NAME_LOCAL_CLAIM); - mockStatic(IdentityUtil.class); when(IdentityUtil.getProperty(SCIMCommonConstants.PRIMARY_LOGIN_IDENTIFIER_CLAIM)) .thenReturn(DISPLAY_NAME_LOCAL_CLAIM); when(IdentityUtil.getProperty(SCIMCommonConstants.ENABLE_LOGIN_IDENTIFIERS)).thenReturn("true"); when(IdentityUtil.extractDomainFromName(anyString())).thenCallRealMethod(); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.convertSCIMtoLocalDialect(anyMap())).thenCallRealMethod(); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMappings); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserList(anyString(), anyString(), anyString())).thenReturn(null); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())) .thenReturn(secondaryUserStoreManager); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java index 466dc8aba..20b6ce6ea 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java @@ -19,12 +19,12 @@ package org.wso2.carbon.identity.scim2.common.listener; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; @@ -33,7 +33,6 @@ import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.scim2.common.DAO.GroupDAO; import org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException; -import org.wso2.carbon.identity.scim2.common.group.SCIMGroupHandler; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.carbon.user.api.Permission; @@ -49,22 +48,14 @@ import java.util.Map; import java.util.UUID; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.mockito.Mockito.*; +import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; -@PrepareForTest({UserCoreUtil.class, SCIMGroupHandler.class, SCIMCommonUtils.class, IdentityUtil.class, - IdentityTenantUtil.class}) -public class SCIMUserOperationListenerTest extends PowerMockTestCase { + +public class SCIMUserOperationListenerTest { private final String CARBON_SUPER = "carbon.super"; private String userName = "testUser"; @@ -93,22 +84,30 @@ public class SCIMUserOperationListenerTest extends PowerMockTestCase { @Mock GroupDAO groupDAO; - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } + private MockedStatic userCoreUtil; + private MockedStatic scimCommonUtils; + private MockedStatic identityTenantUtil; + private MockedStatic identityUtil; @BeforeMethod public void setUp() throws Exception { - + initMocks(this); scimUserOperationListener = spy(new SCIMUserOperationListener()); - mockStatic(UserCoreUtil.class); - mockStatic(SCIMCommonUtils.class); - mockStatic(IdentityTenantUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + identityUtil = mockStatic(IdentityUtil.class); SCIMCommonComponentHolder.setClaimManagementService(claimMetadataManagementService); when(userStoreManager.getTenantId()).thenReturn(-1234); - when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(CARBON_SUPER); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(CARBON_SUPER); + } + + @AfterMethod + public void tearDown() { + userCoreUtil.close(); + scimCommonUtils.close(); + identityTenantUtil.close(); + identityUtil.close(); } @DataProvider(name = "testGetExecutionOrderIdData") @@ -234,8 +233,7 @@ public void testDoPreSetUserClaimValues(boolean isEnabled, boolean isSCIMEnabled when(scimUserOperationListener.isEnable()).thenReturn(isEnabled); when(userStoreManager.isSCIMEnabled()).thenReturn(isSCIMEnabled); - mockStatic(IdentityUtil.class); - when(IdentityUtil.getProperty(FrameworkConstants.ENABLE_JIT_PROVISION_ENHANCE_FEATURE)).thenReturn("false"); + identityUtil.when(() -> IdentityUtil.getProperty(FrameworkConstants.ENABLE_JIT_PROVISION_ENHANCE_FEATURE)).thenReturn("false"); assertTrue(scimUserOperationListener. doPreSetUserClaimValuesWithID(userId, claims, profile, userStoreManager)); @@ -307,19 +305,13 @@ public void testDoPostAddRole1() throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testDoPostAddRole2() throws Exception { mockTestEnvironment(true, true, "testDomain"); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenThrow(new IdentitySCIMException - ("IdentitySCIMException")); - - scimUserOperationListener.doPostAddRoleWithID(roleName, userList, permissions, userStoreManager); - } - - @Test(dataProvider = "testDoPostAddRoleData") - public void testDoPreDeleteRole(boolean isEnabled, boolean isSCIMEnabled, boolean isGroupExisting, - String domainName) throws Exception { - mockTestEnvironment(isEnabled, isSCIMEnabled, domainName); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(isGroupExisting); - - assertTrue(scimUserOperationListener.doPreDeleteRole(roleName, userStoreManager)); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())) + .thenThrow(new IdentitySCIMException("IdentitySCIMException")); + })) { + scimUserOperationListener.doPostAddRoleWithID(roleName, userList, permissions, userStoreManager); + } } @Test(expectedExceptions = UserStoreException.class) @@ -333,10 +325,13 @@ public void testDoPreDeleteRole1() throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testDoPreDeleteRole2() throws Exception { mockTestEnvironment(true, true, "testDomain"); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenThrow(new IdentitySCIMException - ("IdentitySCIMException")); - - scimUserOperationListener.doPreDeleteRole(roleName, userStoreManager); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(nullable(String.class), anyInt())) + .thenThrow(new IdentitySCIMException("IdentitySCIMException")); + })) { + scimUserOperationListener.doPreDeleteRole(roleName, userStoreManager); + } } @Test @@ -363,9 +358,12 @@ public Object[][] testDoPostUpdateRoleNameData() { @Test(dataProvider = "testDoPostUpdateRoleNameData") public void testDoPostUpdateRoleName(boolean isEnabled, boolean isSCIMEnabled, String domainName) throws Exception { mockTestEnvironment(isEnabled, isSCIMEnabled, domainName); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); - - assertTrue(scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager)); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())).thenReturn(true); + })) { + assertTrue(scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager)); + } } @Test(expectedExceptions = UserStoreException.class) @@ -379,10 +377,13 @@ public void testDoPostUpdateRoleName1() throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testDoPostUpdateRoleName2() throws Exception { mockTestEnvironment(true, true, "testDomain"); - when(groupDAO.isExistingGroup(anyString(), anyInt())) - .thenThrow(new IdentitySCIMException("IdentitySCIMException")); - - scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())) + .thenThrow(new IdentitySCIMException("IdentitySCIMException")); + })) { + scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager); + } } @Test @@ -426,7 +427,6 @@ public Object[][] testSCIMAttributesData() { @Test(dataProvider = "testSCIMAttributesData") public void testGetSCIMAttributes(Map claimsMap) throws Exception { - mockStatic(SCIMCommonUtils.class); Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "http://wso2.org/claims/userid"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.CREATED_URI, "http://wso2.org/claims/created"); @@ -435,13 +435,12 @@ public void testGetSCIMAttributes(Map claimsMap) throws Exceptio scimToLocalClaimsMap.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, "http://wso2.org/claims/username"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.RESOURCE_TYPE_URI, "http://wso2.org/claims/resourceType"); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); assertNotNull(scimUserOperationListener.getSCIMAttributes(userName, claimsMap)); } @Test(dataProvider = "testSCIMAttributesData") public void testPopulateSCIMAttributes(Map claimsMap) throws Exception { - mockStatic(SCIMCommonUtils.class); Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "http://wso2.org/claims/userid"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.CREATED_URI, "http://wso2.org/claims/created"); @@ -450,16 +449,15 @@ public void testPopulateSCIMAttributes(Map claimsMap) throws Exc scimToLocalClaimsMap.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, "http://wso2.org/claims/username"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.RESOURCE_TYPE_URI, "http://wso2.org/claims/resourceType"); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); assertNotNull(scimUserOperationListener.populateSCIMAttributes(userName, claimsMap)); } private void mockTestEnvironment(boolean isEnabled, boolean isSCIMEnabled, String domainName) throws Exception { when(scimUserOperationListener.isEnable()).thenReturn(isEnabled); when(userStoreManager.isSCIMEnabled()).thenReturn(isSCIMEnabled); - whenNew(GroupDAO.class).withNoArguments().thenReturn(groupDAO); - when(UserCoreUtil.getDomainName((RealmConfiguration) anyObject())).thenReturn(domainName); - when(UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn("testRoleNameWithDomain"); - when(SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn("testRoleNameWithDomain"); + userCoreUtil.when(() -> UserCoreUtil.getDomainName((RealmConfiguration) any())).thenReturn(domainName); + userCoreUtil.when(() -> UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn("testRoleNameWithDomain"); + scimCommonUtils.when(() ->SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn("testRoleNameWithDomain"); } } diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java index 4ccc36dce..0fde819e8 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java @@ -20,33 +20,25 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.user.core.util.UserCoreUtil; import java.util.Map; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.*; +import static org.mockito.MockitoAnnotations.initMocks; -@PrepareForTest({SCIMCommonComponentHolder.class, ClaimsMgtUtil.class, IdentityTenantUtil.class, UserCoreUtil.class, - IdentityUtil.class, SCIMCommonUtils.class, AdminAttributeUtil.class}) -public class AdminAttributeUtilTest extends PowerMockTestCase { +public class AdminAttributeUtilTest { @Mock RealmService realmService; @@ -59,9 +51,24 @@ public class AdminAttributeUtilTest extends PowerMockTestCase { AdminAttributeUtil adminAttributeUtil; + private MockedStatic scimCommonComponentHolder; + private MockedStatic claimsMgtUtil; + private MockedStatic identityTenantUtil; + @BeforeMethod public void setUp() throws Exception { + initMocks(this); adminAttributeUtil = new AdminAttributeUtil(); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + } + + @AfterMethod + public void tearDown() throws Exception { + scimCommonComponentHolder.close(); + claimsMgtUtil.close(); + identityTenantUtil.close(); } @DataProvider(name = "testUpdateAdminUserData") @@ -76,15 +83,12 @@ public Object[][] testUpdateAdminUserData() { public void testUpdateAdminUser(boolean validateSCIMID) throws Exception { String adminUsername = "admin"; - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenReturn(true); - when(ClaimsMgtUtil.getAdminUserNameFromTenantId(eq(realmService), anyInt())).thenReturn(adminUsername); - when(IdentityTenantUtil.getRealmService()).thenReturn(realmService); + claimsMgtUtil.when(() -> ClaimsMgtUtil.getAdminUserNameFromTenantId(eq(realmService), anyInt())).thenReturn(adminUsername); + identityTenantUtil.when(() -> IdentityTenantUtil.getRealmService()).thenReturn(realmService); when(userStoreManager.getUserClaimValue(anyString(), anyString(), anyString())).thenReturn(""); ArgumentCaptor argument = ArgumentCaptor.forClass(Map.class); @@ -94,10 +98,7 @@ public void testUpdateAdminUser(boolean validateSCIMID) throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testUpdateAdminUser1() throws Exception { - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenThrow(new UserStoreException()); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java index 0377636ae..255f0193e 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java @@ -20,8 +20,9 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -38,18 +39,13 @@ import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.util.UserCoreUtil; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.any; + +import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; -@PrepareForTest({SCIMCommonComponentHolder.class, ClaimsMgtUtil.class, IdentityTenantUtil.class, UserCoreUtil.class, - IdentityUtil.class, SCIMCommonUtils.class, AdminAttributeUtil.class}) -public class AdminAttributeUtilTestForGroup extends PowerMockTestCase { +public class AdminAttributeUtilTestForGroup { @Mock RealmService realmService; @@ -68,9 +64,33 @@ public class AdminAttributeUtilTestForGroup extends PowerMockTestCase { AdminAttributeUtil adminAttributeUtil; + private MockedStatic scimCommonComponentHolder; + private MockedStatic claimsMgtUtil; + private MockedStatic identityTenantUtil; + private MockedStatic userCoreUtil; + private MockedStatic identityUtil; + private MockedStatic scimCommonUtils; + @BeforeMethod public void setUp() throws Exception { + initMocks(this); adminAttributeUtil = new AdminAttributeUtil(); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + identityUtil = mockStatic(IdentityUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + } + + @AfterMethod + public void tearDown() { + scimCommonComponentHolder.close(); + claimsMgtUtil.close(); + identityTenantUtil.close(); + userCoreUtil.close(); + identityUtil.close(); + scimCommonUtils.close(); } @DataProvider(name = "testUpdateAdminUserData") @@ -93,13 +113,7 @@ public Object[][] testUpdateAdminGroupData() { public void testUpdateAdminGroup(String domainName) throws Exception { String roleNameWithDomain = "TESTDOMAIN/admin"; - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(UserCoreUtil.class); - mockStatic(IdentityUtil.class); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenReturn(true); @@ -107,42 +121,38 @@ public void testUpdateAdminGroup(String domainName) throws Exception { when(userStoreManager.getRealmConfiguration()).thenReturn(realmConfiguration); when(userStoreManager.isRoleAndGroupSeparationEnabled()).thenReturn(true); when(realmConfiguration.getAdminRoleName()).thenReturn("admin"); - when(UserCoreUtil.getDomainName((RealmConfiguration) anyObject())).thenReturn(domainName); - when(IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); - when(UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); - when(SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); - whenNew(SCIMGroupHandler.class).withAnyArguments().thenReturn(scimGroupHandler); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; - adminAttributeUtil.updateAdminGroup(1); - verify(scimGroupHandler).addMandatoryAttributes(argument.capture()); - - assertEquals(argument.getValue(), roleNameWithDomain); + userCoreUtil.when(() -> UserCoreUtil.getDomainName((RealmConfiguration) any())).thenReturn(domainName); + identityUtil.when(() -> IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); + userCoreUtil.when(() -> UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); + scimCommonUtils.when(() -> SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); + + try (MockedConstruction mocked = mockConstruction(SCIMGroupHandler.class, (mock, context) -> { + when(mock.isGroupExisting(anyString())).thenReturn(false); + })) { + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; + adminAttributeUtil.updateAdminGroup(1); + verify(mocked.constructed().get(0)).addMandatoryAttributes(argument.capture()); + + assertEquals(argument.getValue(), roleNameWithDomain); + } } @Test(expectedExceptions = IdentitySCIMException.class) public void testUpdateAdminGroup1() throws Exception { String roleNameWithDomain = "TESTDOMAIN/admin"; - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(UserCoreUtil.class); - mockStatic(IdentityUtil.class); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenReturn(true); when(userStoreManager.getTenantId()).thenReturn(1); when(userStoreManager.getRealmConfiguration()).thenReturn(realmConfiguration); when(realmConfiguration.getAdminRoleName()).thenReturn("admin"); - when(UserCoreUtil.getDomainName((RealmConfiguration) anyObject())).thenReturn("testDomain"); - when(IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); - when(UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); - when(SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); - whenNew(SCIMGroupHandler.class).withAnyArguments().thenReturn(scimGroupHandler); + userCoreUtil.when(() -> UserCoreUtil.getDomainName((RealmConfiguration) any())).thenReturn("testDomain"); + identityUtil.when(() -> IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); + userCoreUtil.when(() -> UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); + scimCommonUtils.when(() -> SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); when(scimGroupHandler.isGroupExisting(anyString())).thenThrow(new IdentitySCIMException("testException")); adminAttributeUtil.updateAdminGroup(1); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java index 21b298c53..493cdb9d0 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java @@ -19,14 +19,10 @@ package org.wso2.carbon.identity.scim2.common.utils; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; +import org.mockito.MockedStatic; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.CarbonBaseConstants; @@ -41,16 +37,13 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; - -@PrepareForTest({IdentityUtil.class, UserCoreUtil.class, IdentityTenantUtil.class, ServiceURLBuilder.class}) -@PowerMockIgnore({"javax.xml.*","org.w3c.dom.*","org.xml.sax.*"}) -public class SCIMCommonUtilsTest extends PowerMockTestCase { +public class SCIMCommonUtilsTest { private static final String ID = "8a439cf6-3c6b-47d2-94bf-34d072495af3"; private static final String SCIM_URL = "https://localhost:9443/scim2"; @@ -71,39 +64,43 @@ public class SCIMCommonUtilsTest extends PowerMockTestCase { @Mock DefaultServiceURLBuilder defaultServiceURLBuilder1; - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } + private MockedStatic userCoreUtil; + private MockedStatic identityTenantUtil; + private MockedStatic serviceURLBuilder; + private MockedStatic identityUtil; @BeforeMethod public void setUp() throws Exception { initMocks(this); - mockStatic(IdentityUtil.class); - mockStatic(UserCoreUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(ServiceURLBuilder.class); - when(IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn(SCIM_URL); - when(IdentityUtil.getPrimaryDomainName()).thenReturn(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME); - when(ServiceURLBuilder.create()).thenReturn(defaultServiceURLBuilder); + identityUtil = mockStatic(IdentityUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + identityUtil.when(() -> IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn(SCIM_URL); + identityUtil.when(() -> IdentityUtil.getPrimaryDomainName()).thenReturn(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME); + serviceURLBuilder.when(() -> ServiceURLBuilder.create()).thenReturn(defaultServiceURLBuilder); when(defaultServiceURLBuilder.build()).thenReturn(serviceURL); when(defaultServiceURLBuilder.addPath(SCIMCommonConstants.SCIM2_ENDPOINT)).thenReturn (defaultServiceURLBuilder1); when(defaultServiceURLBuilder1.build()).thenReturn(serviceURL1); when(serviceURL1.getAbsolutePublicURL()).thenReturn("https://localhost:9443/scim2"); when(serviceURL.getAbsolutePublicURL()).thenReturn("https://localhost:9443"); - when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn("carbon.super"); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomainFromContext()).thenReturn("carbon.super"); } @AfterMethod - public void tearDown() throws Exception { + public void tearDown() { + identityUtil.close(); + userCoreUtil.close(); + identityTenantUtil.close(); + serviceURLBuilder.close(); System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMUserURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimUserURL = SCIMCommonUtils.getSCIMUserURL(ID); assertEquals(scimUserURL, scimUserLocation + "/" + ID); } @@ -111,7 +108,7 @@ public void testGetSCIMUserURL(boolean isTenantQualifyURLEnabled) throws Excepti @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMUserURLForNullId(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimUserURL = SCIMCommonUtils.getSCIMUserURL(null); assertEquals(scimUserURL, null); } @@ -119,7 +116,7 @@ public void testGetSCIMUserURLForNullId(boolean isTenantQualifyURLEnabled) throw @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMGroupURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimGroupURL = SCIMCommonUtils.getSCIMGroupURL(ID); assertEquals(scimGroupURL, scimGroupLocation + "/" + ID); } @@ -127,7 +124,7 @@ public void testGetSCIMGroupURL(boolean isTenantQualifyURLEnabled) throws Except @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMGroupURLForNullId(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimGroupURL = SCIMCommonUtils.getSCIMGroupURL(null); assertEquals(scimGroupURL, null); } @@ -135,7 +132,7 @@ public void testGetSCIMGroupURLForNullId(boolean isTenantQualifyURLEnabled) thro @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMServiceProviderConfigURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimServiceProviderConfigURL = SCIMCommonUtils.getSCIMServiceProviderConfigURL(ID); assertEquals(scimServiceProviderConfigURL, scimServiceProviderConfig); } @@ -143,7 +140,7 @@ public void testGetSCIMServiceProviderConfigURL(boolean isTenantQualifyURLEnable @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMUserURL1(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimUsersURL = SCIMCommonUtils.getSCIMUserURL(); assertEquals(scimUsersURL, scimUserLocation); } @@ -151,7 +148,7 @@ public void testGetSCIMUserURL1(boolean isTenantQualifyURLEnabled) throws Except @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMGroupURL1(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimGroupsURL = SCIMCommonUtils.getSCIMGroupURL(); assertEquals(scimGroupsURL, scimGroupLocation); } @@ -159,7 +156,7 @@ public void testGetSCIMGroupURL1(boolean isTenantQualifyURLEnabled) throws Excep @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMServiceProviderConfigURL1(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimServiceProviderConfigURL = SCIMCommonUtils.getSCIMServiceProviderConfigURL(); assertEquals(scimServiceProviderConfigURL, scimServiceProviderConfig); } @@ -167,7 +164,7 @@ public void testGetSCIMServiceProviderConfigURL1(boolean isTenantQualifyURLEnabl @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMResourceTypeURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimResourceTypeURL = SCIMCommonUtils.getSCIMResourceTypeURL(); assertEquals(scimResourceTypeURL, scimResourceType); } @@ -249,7 +246,7 @@ public void testSetThreadLocalIsManagedThroughSCIMEP(Boolean value, Boolean expe public void testGetGlobalConsumerId() throws Exception { String tenantDomain = "testTenantDomain"; CommonTestUtils.initPrivilegedCarbonContext(tenantDomain); - when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantDomain); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantDomain); assertEquals(SCIMCommonUtils.getGlobalConsumerId(), tenantDomain); } @@ -257,7 +254,7 @@ public void testGetGlobalConsumerId() throws Exception { public void testGetUserConsumerId() throws Exception { String userConsumerId = "testConsumerId"; CommonTestUtils.initPrivilegedCarbonContext(); - when(UserCoreUtil.addTenantDomainToEntry(anyString(), anyString())).thenReturn(userConsumerId); + userCoreUtil.when(() -> UserCoreUtil.addTenantDomainToEntry(anyString(), anyString())).thenReturn(userConsumerId); assertEquals(SCIMCommonUtils.getUserConsumerId(), userConsumerId); } diff --git a/pom.xml b/pom.xml index 52d30c9ba..1d84407dd 100644 --- a/pom.xml +++ b/pom.xml @@ -230,15 +230,9 @@ test - org.powermock - powermock-module-testng - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} + org.mockito + mockito-testng + ${mockito-testng.version} test @@ -328,12 +322,12 @@ 1.7.21 - 6.9.10 + 7.10.1 0.8.4 - 2.23.4 - 2.0.2 - 2.22.2 + 3.2.5 + 5.3.1 + 0.5.2 1.10.1