From 7a609194ae7f3c624ef74436d73c668348acec49 Mon Sep 17 00:00:00 2001 From: Emi-Polliotti Date: Mon, 16 Dec 2024 09:43:43 -0300 Subject: [PATCH 1/4] Feature ETP-870: Add unit tests for the ReportValuationStock module --- .../handler/ReportValuationStock.java | 2 +- .../ETRVSComponentProviderTest.java | 79 +++++++ .../handler/CostingRuleUtilsTest.java | 102 ++++++++ ...ReportValuationStockAddParametersTest.java | 146 ++++++++++++ .../ReportValuationStockBuildDataTest.java | 155 ++++++++++++ .../ReportValuationStockCostTypeTest.java | 135 +++++++++++ .../ReportValuationStockGetReportTest.java | 215 +++++++++++++++++ .../ReportValuationStockParametersTest.java | 136 +++++++++++ .../ReportValuationStockPrintTest.java | 221 ++++++++++++++++++ .../ReportValuationStockSummaryTest.java | 174 ++++++++++++++ .../ReportValuationStockWarehousesTest.java | 165 +++++++++++++ 11 files changed, 1529 insertions(+), 1 deletion(-) create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/ETRVSComponentProviderTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockCostTypeTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java diff --git a/modules_core/com.etendoerp.reportvaluationstock/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStock.java b/modules_core/com.etendoerp.reportvaluationstock/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStock.java index faa0869f6..4a6a63dbe 100644 --- a/modules_core/com.etendoerp.reportvaluationstock/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStock.java +++ b/modules_core/com.etendoerp.reportvaluationstock/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStock.java @@ -101,7 +101,7 @@ protected JRDataSource getReportData(Map parameters) { return (JRFieldProviderDataSource) jrParams.get(PARAM_SUB_REPORT); } - private void buildData(VariablesSecureApp vars, String strDate, + protected void buildData(VariablesSecureApp vars, String strDate, String strOrganization, String strWarehouse, String strCategoryProduct, String strCurrencyId, boolean isWarehouseConsolidation, Map parameters) throws ServletException { ReportValuationStockData[] data; diff --git a/src-test/src/com/etendoerp/reportvaluationstock/ETRVSComponentProviderTest.java b/src-test/src/com/etendoerp/reportvaluationstock/ETRVSComponentProviderTest.java new file mode 100644 index 000000000..05e610dfc --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/ETRVSComponentProviderTest.java @@ -0,0 +1,79 @@ +package com.etendoerp.reportvaluationstock; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; +import org.openbravo.client.kernel.BaseComponentProvider; + +import java.util.List; +import java.util.HashMap; + +/** + * Unit tests for the {@link ETRVSComponentProvider} class. + *

+ * This class tests the behavior of the component provider methods, ensuring + * correct handling of global component resources and specific components. + *

+ */ +public class ETRVSComponentProviderTest { + + private ETRVSComponentProvider componentProvider; + + /** + * Sets up the test environment by initializing the component provider instance. + */ + @Before + public void setUp() { + componentProvider = new ETRVSComponentProvider(); + } + + /** + * Tests the {@link ETRVSComponentProvider(String, HashMap)} method. + *

+ * Ensures that the method returns null when provided with an arbitrary ID and empty parameters. + *

+ */ + @Test + public void testGetComponent() { + assertNull(componentProvider.getComponent("testId", new HashMap<>())); + } + + /** + * Tests the {@link ETRVSComponentProvider#getGlobalComponentResources()} method. + *

+ * Verifies that the method returns a non-null list containing a single valid resource. + *

+ */ + @Test + public void testGetGlobalComponentResources() { + List resources = componentProvider.getGlobalComponentResources(); + + assertNotNull(resources); + + assertEquals(1, resources.size()); + + BaseComponentProvider.ComponentResource resource = resources.get(0); + assertNotNull(resource); + + assertEquals( + "web/com.etendoerp.reportvaluationstock/js/etrvs-onchange.js", + resource.getPath() + ); + + } + + /** + * Tests that {@link ETRVSComponentProvider#getGlobalComponentResources()} returns a non-empty list. + *

+ * Ensures the presence of global component resources. + *

+ */ + @Test + public void testGetGlobalComponentResourcesNotEmpty() { + assertFalse(componentProvider.getGlobalComponentResources().isEmpty()); + } +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java new file mode 100644 index 000000000..5ce46d855 --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java @@ -0,0 +1,102 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; +import org.junit.Before; +import org.openbravo.dal.service.OBQuery; +import org.openbravo.model.common.enterprise.Organization; +import org.openbravo.dal.service.OBDal; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.openbravo.model.materialmgmt.cost.CostingRule; + +import java.lang.reflect.Method; + +/** + * Test class for CostingRuleUtils, which verifies the logic related + * to the calculation of costing rules based on organizations. + */ +public class CostingRuleUtilsTest { + + private Organization mockOrganization; + private OBDal mockOBDal; + private Method getLEsCostingAlgortithmMethod; + + /** + * Sets up the initial state required for the tests. Prepare mocks and retrieves + * the reflected method from ReportValuationStock for testing purposes. + * + * @throws Exception if an error occurs during the setup. + */ + @Before + public void setUp() throws Exception { + getLEsCostingAlgortithmMethod = ReportValuationStock.class.getDeclaredMethod("getLEsCostingAlgortithm", Organization.class); + getLEsCostingAlgortithmMethod.setAccessible(true); + + mockOrganization = Mockito.mock(Organization.class); + mockOBDal = Mockito.mock(OBDal.class); + } + + /** + * Tests the getLEsCostingAlgortithm method with a valid organization. Verifies that + * the method returns the expected costing rule when provided with correct data. + * + * @throws Exception if an error occurs during the test execution. + */ + @Test + public void testGetLEsCostingAlgortithmWithValidOrganization() throws Exception { + String orgId = "TEST_ORG_ID"; + CostingRule expectedRule = Mockito.mock(CostingRule.class); + + Mockito.when(mockOrganization.getId()).thenReturn(orgId); + + try (MockedStatic mockedStatic = Mockito.mockStatic(OBDal.class)) { + mockedStatic.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); + + OBQuery mockQuery = Mockito.mock(OBQuery.class); + Mockito.when(mockOBDal.createQuery(Mockito.eq(CostingRule.class), Mockito.anyString())) + .thenReturn(mockQuery); + Mockito.when(mockQuery.setNamedParameter(Mockito.eq("orgId"), Mockito.eq(orgId))) + .thenReturn(mockQuery); + Mockito.when(mockQuery.setMaxResult(1)).thenReturn(mockQuery); + Mockito.when(mockQuery.uniqueResult()).thenReturn(expectedRule); + + CostingRule result = (CostingRule) getLEsCostingAlgortithmMethod.invoke(null, mockOrganization); + + assertNotNull("El resultado no debería ser null", result); + assertEquals("El resultado debería ser el CostingRule esperado", expectedRule, result); + } + } + + /** + * Tests the getLEsCostingAlgortithm method when no costing rules are found. + * Verifies that the method returns null when no results are available. + * + * @throws Exception if an error occurs during the test execution. + */ + @Test + public void testGetLEsCostingAlgortithmNoRulesFound() throws Exception { + String orgId = "TEST_ORG_ID"; + + Mockito.when(mockOrganization.getId()).thenReturn(orgId); + + try (MockedStatic mockedStatic = Mockito.mockStatic(OBDal.class)) { + mockedStatic.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); + + OBQuery mockQuery = Mockito.mock(OBQuery.class); + Mockito.when(mockOBDal.createQuery(Mockito.eq(CostingRule.class), Mockito.anyString())) + .thenReturn(mockQuery); + Mockito.when(mockQuery.setNamedParameter(Mockito.eq("orgId"), Mockito.eq(orgId))) + .thenReturn(mockQuery); + Mockito.when(mockQuery.setMaxResult(1)).thenReturn(mockQuery); + Mockito.when(mockQuery.uniqueResult()).thenReturn(null); + + CostingRule result = (CostingRule) getLEsCostingAlgortithmMethod.invoke(null, mockOrganization); + + assertNull("El resultado debería ser null cuando no se encuentran reglas", result); + } + } +} diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java new file mode 100644 index 000000000..b471cd39a --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java @@ -0,0 +1,146 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.servlet.ServletException; + +import org.codehaus.jettison.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.model.domaintype.DateDomainType; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.base.session.OBPropertiesProvider; +import org.openbravo.client.application.ApplicationConstants; +import org.openbravo.client.application.ReportDefinition; +import org.openbravo.client.kernel.RequestContext; +import org.openbravo.dal.core.OBContext; +import org.openbravo.erpCommon.utility.OBMessageUtils; + +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockAddParametersTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Mock + private ReportDefinition mockProcess; + + @Mock + private RequestContext mockRequestContext; + + @Mock + private VariablesSecureApp mockVars; + + @Mock + private OBPropertiesProvider mockPropertiesProvider; + + @Mock + private Properties mockProperties; + + private MockedStatic mockedRequestContext; + private MockedStatic mockedPropertiesProvider; + private MockedStatic mockedOBContext; + private MockedStatic mockedOBMessageUtils; + + private ReportValuationStock reportValuationStock; + + private static final String TEST_ORG_ID = "testOrgId"; + private static final String TEST_WAREHOUSE_ID = "testWarehouseId"; + private static final String TEST_CATEGORY_ID = "testCategoryId"; + private static final String TEST_CURRENCY_ID = "testCurrencyId"; + private static final String TEST_DATE = "2024-01-01"; + + @Before + public void setUp() throws ServletException { + reportValuationStock = spy(new ReportValuationStock()); + + mockedRequestContext = mockStatic(RequestContext.class); + mockedPropertiesProvider = mockStatic(OBPropertiesProvider.class); + mockedOBContext = mockStatic(OBContext.class); + mockedOBMessageUtils = mockStatic(OBMessageUtils.class); + + mockedRequestContext.when(RequestContext::get).thenReturn(mockRequestContext); + mockedPropertiesProvider.when(OBPropertiesProvider::getInstance).thenReturn(mockPropertiesProvider); + + mockedOBMessageUtils.when(() -> OBMessageUtils.translateError(anyString())) + .thenReturn(null); + mockedOBMessageUtils.when(() -> OBMessageUtils.messageBD(anyString())) + .thenReturn("Test Message"); + + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockPropertiesProvider.getOpenbravoProperties()).thenReturn(mockProperties); + when(mockProperties.getProperty("dateFormat.java")).thenReturn("yyyy-MM-dd"); + + doNothing().when(reportValuationStock).buildData( + any(VariablesSecureApp.class), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + any(Boolean.class), + any(Map.class) + ); + } + + @After + public void tearDown() { + if (mockedRequestContext != null) { + mockedRequestContext.close(); + } + if (mockedPropertiesProvider != null) { + mockedPropertiesProvider.close(); + } + if (mockedOBContext != null) { + mockedOBContext.close(); + } + if (mockedOBMessageUtils != null) { + mockedOBMessageUtils.close(); + } + } + + @Test + public void testAddAdditionalParametersValidInput() throws Exception { + Map parameters = new HashMap<>(); + JSONObject jsonContent = new JSONObject(); + JSONObject params = new JSONObject(); + + params.put("AD_Org_ID", TEST_ORG_ID); + params.put("M_Warehouse_ID", TEST_WAREHOUSE_ID); + params.put("WarehouseConsolidation", true); + params.put("M_Product_Category_ID", TEST_CATEGORY_ID); + params.put("C_Currency_ID", TEST_CURRENCY_ID); + params.put("Date", TEST_DATE); + + jsonContent.put("_params", params); + jsonContent.put(ApplicationConstants.BUTTON_VALUE, "PDF"); + + mock(DateDomainType.class); + + reportValuationStock.addAdditionalParameters(mockProcess, jsonContent, parameters); + + assertNotNull("Parameters should not be null", parameters); + assertEquals("PDF", parameters.get("OUTPUT_FORMAT")); + } + + +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java new file mode 100644 index 000000000..f386c6cc4 --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java @@ -0,0 +1,155 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletException; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.dal.core.OBContext; +import org.openbravo.dal.security.OrganizationStructureProvider; +import org.openbravo.dal.service.OBDal; +import org.openbravo.model.ad.system.Client; +import org.openbravo.model.common.enterprise.Organization; +import org.openbravo.service.db.DalConnectionProvider; +import org.openbravo.erpCommon.utility.OBError; +import org.openbravo.erpCommon.utility.OBMessageUtils; + +/** + * Test class for ReportValuationStock, verifying the behavior of the + * buildData method under various scenarios. + */ +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockBuildDataTest { + + /** + * Rule to handle expected exceptions in test cases. + */ + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @InjectMocks + private ReportValuationStock reportValuationStock; + + @Mock + private VariablesSecureApp vars; + + @Mock + private Organization mockOrg; + + @Mock + private Client mockClient; + + @Mock + private OrganizationStructureProvider mockOsp; + + private Method buildDataMethod; + private static final String TEST_DATE = "2024-01-01"; + private static final String TEST_ORG_ID = "testOrgId"; + private static final String TEST_WAREHOUSE_ID = "testWarehouseId"; + private static final String TEST_CATEGORY_ID = "testCategoryId"; + private static final String TEST_CURRENCY_ID = "testCurrencyId"; + private static final String TEST_CLIENT_ID = "testClientId"; + + /** + * Sets up the initial state required for the tests. Prepare mocks and retrieves + * the reflected buildData method for testing. + * + * @throws Exception if an error occurs during the setup. + */ + @Before + public void setUp() throws Exception { + buildDataMethod = ReportValuationStock.class.getDeclaredMethod( + "buildData", + VariablesSecureApp.class, + String.class, + String.class, + String.class, + String.class, + String.class, + boolean.class, + Map.class + ); + buildDataMethod.setAccessible(true); + + when(mockClient.getId()).thenReturn(TEST_CLIENT_ID); + + Set orgTree = new HashSet<>(); + orgTree.add(TEST_ORG_ID); + } + + /** + * Tests the buildData method when the legal entity is null. Verifies that a + * ServletException is thrown with the expected error message. + */ + @Test + public void testBuildDataWithNullLegalEntity() { + Map parameters = new HashMap<>(); + + try (MockedStatic obDalMock = mockStatic(OBDal.class); + MockedStatic obContextMock = mockStatic(OBContext.class); + MockedStatic connectionProviderMock = mockStatic(DalConnectionProvider.class); + MockedStatic obMessageUtilsMock = mockStatic(OBMessageUtils.class)) { + + OBDal mockOBDal = mock(OBDal.class); + obDalMock.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); + + OBContext mockContext = mock(OBContext.class); + when(mockContext.getCurrentClient()).thenReturn(mockClient); + when(mockContext.getOrganizationStructureProvider(anyString())).thenReturn(mockOsp); + obContextMock.when(OBContext::getOBContext).thenReturn(mockContext); + + DalConnectionProvider mockProvider = mock(DalConnectionProvider.class); + connectionProviderMock.when(DalConnectionProvider::getReadOnlyConnectionProvider) + .thenReturn(mockProvider); + + when(mockOBDal.get(eq(Organization.class), anyString())).thenReturn(mockOrg); + when(mockOsp.getLegalEntity(any(Organization.class))).thenReturn(null); + + OBError mockError = mock(OBError.class); + when(mockError.getMessage()).thenReturn("WarehouseNotInLE"); + obMessageUtilsMock.when(() -> OBMessageUtils.messageBD(anyString())) + .thenReturn("WarehouseNotInLE"); + obMessageUtilsMock.when(() -> OBMessageUtils.translateError(anyString())) + .thenReturn(mockError); + + try { + buildDataMethod.invoke( + reportValuationStock, + vars, + TEST_DATE, + TEST_ORG_ID, + TEST_WAREHOUSE_ID, + TEST_CATEGORY_ID, + TEST_CURRENCY_ID, + false, + parameters + ); + } catch (Exception e) { + assertTrue("Expected ServletException", e.getCause() instanceof ServletException); + assertTrue("Expected correct error message", + e.getCause().getMessage().contains("WarehouseNotInLE")); + } + } + } +} diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockCostTypeTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockCostTypeTest.java new file mode 100644 index 000000000..237185e42 --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockCostTypeTest.java @@ -0,0 +1,135 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.costing.AverageAlgorithm; +import org.openbravo.costing.StandardAlgorithm; +import org.openbravo.model.materialmgmt.cost.CostingAlgorithm; + +/** + * Unit tests for the cost type determination logic in the {@link ReportValuationStock} class. + * This class verifies the behavior of the `getCostType` method when handling + * different costing algorithms. + */ +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockCostTypeTest { + + @InjectMocks + private ReportValuationStock reportValuationStock; + + @Mock + private CostingAlgorithm mockCostingAlgorithm; + + private Method getCostTypeMethod; + + /** + * Sets up the test environment by initializing the required objects + * and preparing the `getCostType` method for reflective invocation. + * + * @throws Exception if reflection setup fails + */ + @Before + public void setUp() throws Exception { + getCostTypeMethod = ReportValuationStock.class.getDeclaredMethod( + "getCostType", + CostingAlgorithm.class + ); + getCostTypeMethod.setAccessible(true); + } + + /** + * Tests the `getCostType` method for a costing algorithm of type {@link AverageAlgorithm}. + * + * @throws Exception if the method invocation or mock setup fails + */ + @Test + public void testGetCostTypeWithAverageAlgorithm() throws Exception { + when(mockCostingAlgorithm.getJavaClassName()) + .thenReturn(TestAverageAlgorithm.class.getName()); + + String result = (String) getCostTypeMethod.invoke( + reportValuationStock, + mockCostingAlgorithm + ); + + assertEquals("Should return AVA for Average Algorithm", "'AVA'", result); + } + + /** + * Tests the `getCostType` method for a costing algorithm of type {@link StandardAlgorithm}. + * + * @throws Exception if the method invocation or mock setup fails + */ + @Test + public void testGetCostTypeWithStandardAlgorithm() throws Exception { + when(mockCostingAlgorithm.getJavaClassName()) + .thenReturn(TestStandardAlgorithm.class.getName()); + + String result = (String) getCostTypeMethod.invoke( + reportValuationStock, + mockCostingAlgorithm + ); + + assertEquals("Should return STA for Standard Algorithm", "'STA'", result); + } + + /** + * Tests the `getCostType` method for an unknown costing algorithm type. + * + * @throws Exception if the method invocation or mock setup fails + */ + @Test + public void testGetCostTypeWithUnknownAlgorithm() throws Exception { + when(mockCostingAlgorithm.getJavaClassName()) + .thenReturn(String.class.getName()); + + String result = (String) getCostTypeMethod.invoke( + reportValuationStock, + mockCostingAlgorithm + ); + + assertNull("Should return null for unknown algorithm type", result); + } + + /** + * Tests the `getCostType` method when the provided class name does not exist. + * + * @throws Exception if the method invocation or mock setup fails + */ + @Test + public void testGetCostTypeWithNonexistentClass() throws Exception { + when(mockCostingAlgorithm.getJavaClassName()) + .thenReturn("com.nonexistent.Class"); + + String result = (String) getCostTypeMethod.invoke( + reportValuationStock, + mockCostingAlgorithm + ); + + assertNull("Should return null when class is not found", result); + } + + /** + * Mock implementation of the {@link AverageAlgorithm} for testing purposes. + */ + public static class TestAverageAlgorithm extends AverageAlgorithm { + // Empty class for testing only + } + + /** + * Mock implementation of the {@link StandardAlgorithm} for testing purposes. + */ + public static class TestStandardAlgorithm extends StandardAlgorithm { + // Empty class for testing only + } +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java new file mode 100644 index 000000000..9945de1b0 --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java @@ -0,0 +1,215 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.codehaus.jettison.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.exception.OBException; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.client.application.ReportDefinition; +import org.openbravo.database.ConnectionProvider; +import org.openbravo.erpCommon.utility.JRFieldProviderDataSource; +import org.openbravo.model.common.enterprise.Organization; + +import net.sf.jasperreports.engine.JRDataSource; + +/** + * Unit tests for the {@link ReportValuationStock} class. + * This class uses Mockito to mock dependencies and test different + * scenarios for the Report Valuation Stock functionality. + */ +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockGetReportTest { + + @Mock + private VariablesSecureApp vars; + + @Mock + private ConnectionProvider readOnlyCP; + + @Mock + private Organization filterOrg; + + @Mock + private ReportDefinition mockProcess; + + @Mock + private ReportValuationStockData mockData; + + private ReportValuationStock reportValuationStock; + private Method getReportValuationStockDataMethod; + + private static final String TEST_DATE = "2024-01-01"; + private static final String TEST_CATEGORY = "TEST_CATEGORY"; + private static final String TEST_CURRENCY = "102"; + private static final String TEST_WAREHOUSE = "TEST_WAREHOUSE"; + private static final String TEST_ORG = "TEST_ORG"; + private static final String TEST_CLIENT = "TEST_CLIENT"; + private static final String TEST_LANGUAGE = "en_US"; + + /** + * Sets up the test environment by initializing the required objects + * and configuring mock behaviors. + * + * @throws Exception if reflection or setup fails + */ + @Before + public void setUp() throws Exception { + reportValuationStock = new ReportValuationStock(); + + getReportValuationStockDataMethod = ReportValuationStock.class.getDeclaredMethod( + "getReportValuationStockData", + VariablesSecureApp.class, String.class, String.class, String.class, + boolean.class, String.class, String.class, String.class, String.class, + ConnectionProvider.class, Organization.class, String.class, String.class, + String.class, String.class, String.class, String.class, String.class + ); + getReportValuationStockDataMethod.setAccessible(true); + + when(vars.getLanguage()).thenReturn(TEST_LANGUAGE); + } + + /** + * Tests the retrieval of report data with cost type enabled + * and no warehouse consolidation. + * + * @throws Exception if the method invocation or mocks fail + */ + @Test + public void testGetReportDataWithCostTypeAndNoWarehouseConsolidation() throws Exception { + ReportValuationStockData[] expectedData = new ReportValuationStockData[] { mockData }; + + try (MockedStatic mockedStatic = mockStatic(ReportValuationStockData.class)) { + mockedStatic.when(() -> ReportValuationStockData.select( + eq(readOnlyCP), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString()) + ).thenReturn(expectedData); + + ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( + reportValuationStock, + vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, "processTime", + "N", "STA", TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, + "orgIds", TEST_ORG, TEST_CLIENT, "dateNext", "maxAggDate", "dateFormat" + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should return expected data length", expectedData.length, result.length); + assertEquals("Should return expected data", expectedData[0], result[0]); + } + } + + /** + * Tests the retrieval of report data without cost type + * and with warehouse consolidation enabled. + * + * @throws Exception if the method invocation or mocks fail + */ + @Test + public void testGetReportDataWithoutCostTypeAndWithWarehouseConsolidation() throws Exception { + ReportValuationStockData[] expectedData = new ReportValuationStockData[] { mockData }; + + try (MockedStatic mockedStatic = mockStatic(ReportValuationStockData.class)) { + mockedStatic.when(() -> ReportValuationStockData.selectClusteredByWarehouseWithoutCost( + eq(readOnlyCP), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString()) + ).thenReturn(expectedData); + + ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( + reportValuationStock, + vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, true, "processTime", + "N", null, TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, + "orgIds", TEST_ORG, TEST_CLIENT, "dateNext", "maxAggDate", "dateFormat" + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should return expected data length", expectedData.length, result.length); + assertEquals("Should return expected data", expectedData[0], result[0]); + } + } + + /** + * Tests the retrieval of report data without cost type + * and no warehouse consolidation. + * + * @throws Exception if the method invocation or mocks fail + */ + @Test + public void testGetReportDataWithoutCostTypeAndNoWarehouseConsolidation() throws Exception { + ReportValuationStockData[] expectedData = new ReportValuationStockData[] { mockData }; + + try (MockedStatic mockedStatic = mockStatic(ReportValuationStockData.class)) { + mockedStatic.when(() -> ReportValuationStockData.selectWithoutCost( + eq(readOnlyCP), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString()) + ).thenReturn(expectedData); + + ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( + reportValuationStock, + vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, "processTime", + "N", null, TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, + "orgIds", TEST_ORG, TEST_CLIENT, "dateNext", "maxAggDate", "dateFormat" + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should return expected data length", expectedData.length, result.length); + assertEquals("Should return expected data", expectedData[0], result[0]); + } + } + + /** + * Tests the generation of report data using parameters + * provided in a map. + */ + @Test + public void testGetReportData() { + Map parameters = new HashMap<>(); + HashMap jasperParams = new HashMap<>(); + parameters.put("JASPER_REPORT_PARAMETERS", jasperParams); + + JRFieldProviderDataSource mockDataSource = mock(JRFieldProviderDataSource.class); + jasperParams.put("SUMMARY_DATASET", mockDataSource); + + JRDataSource result = reportValuationStock.getReportData(parameters); + + assertNotNull("Should return data source", result); + assertEquals("Should return correct data source", mockDataSource, result); + } + + /** + * Tests the addition of additional parameters to the report with + * an invalid date format, expecting an {@link OBException}. + * + * @throws Exception if JSON manipulation fails + */ + @Test(expected = OBException.class) + public void testAddAdditionalParametersInvalidDate() throws Exception { + Map parameters = new HashMap<>(); + JSONObject jsonContent = new JSONObject(); + JSONObject params = new JSONObject(); + + params.put("AD_Org_ID", "testOrgId"); + params.put("Date", "invalid-date"); + jsonContent.put("_params", params); + + reportValuationStock.addAdditionalParameters(mockProcess, jsonContent, parameters); + } +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java new file mode 100644 index 000000000..25d76d40e --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java @@ -0,0 +1,136 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.codehaus.jettison.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.exception.OBException; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.base.session.OBPropertiesProvider; +import org.openbravo.client.application.ReportDefinition; +import org.openbravo.client.kernel.RequestContext; +import org.openbravo.erpCommon.utility.OBError; +import org.openbravo.erpCommon.utility.OBMessageUtils; + +/** + * Unit tests for the {@link ReportValuationStock} class. + * + *

This class is responsible for testing the functionality of the + * {@code addAdditionalParameters} method in the {@code ReportValuationStock} class. + * + *

Tests include scenarios for invalid dates and missing required parameters. + */ +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockParametersTest { + + private static final String TEST_ORG_ID = "testOrgId"; + + + @Mock + private ReportDefinition mockProcess; + + @Mock + private RequestContext mockRequestContext; + + @Mock + private VariablesSecureApp mockVars; + + @Mock + private OBPropertiesProvider mockPropertiesProvider; + + + @Mock + private OBError mockError; + + private ReportValuationStock reportValuationStock; + private MockedStatic mockedRequestContext; + private MockedStatic mockedPropertiesProvider; + private MockedStatic mockedMessageUtils; + + /** + * Sets up the test environment by initializing mocks and static instances. + */ + @Before + public void setUp() { + reportValuationStock = new ReportValuationStock() { + }; + + mockedRequestContext = mockStatic(RequestContext.class); + mockedPropertiesProvider = mockStatic(OBPropertiesProvider.class); + mockedMessageUtils = mockStatic(OBMessageUtils.class); + + mockedRequestContext.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + + mockedPropertiesProvider.when(OBPropertiesProvider::getInstance) + .thenReturn(mockPropertiesProvider); + + mockedMessageUtils.when(() -> OBMessageUtils.translateError(anyString())) + .thenReturn(mockError); + } + + /** + * Cleans up the mocked static instances after each test. + */ + @After + public void tearDown() { + if (mockedRequestContext != null) { + mockedRequestContext.close(); + } + if (mockedPropertiesProvider != null) { + mockedPropertiesProvider.close(); + } + if (mockedMessageUtils != null) { + mockedMessageUtils.close(); + } + } + + /** + * Tests the {@code addAdditionalParameters} method for invalid date format. + * + *

Expects an {@link OBException} to be thrown when the date format is invalid. + * + * @throws Exception if the test fails unexpectedly + */ + @Test(expected = OBException.class) + public void testAddAdditionalParametersInvalidDate() throws Exception { + Map parameters = new HashMap<>(); + JSONObject jsonContent = new JSONObject(); + JSONObject params = new JSONObject(); + + params.put("AD_Org_ID", TEST_ORG_ID); + params.put("Date", "invalid-date"); + jsonContent.put("_params", params); + + reportValuationStock.addAdditionalParameters(mockProcess, jsonContent, parameters); + } + + /** + * Tests the {@code addAdditionalParameters} method for missing required parameters. + * + *

Expects an {@link OBException} to be thrown when a required parameter is missing. + * + * @throws Exception if the test fails unexpectedly + */ + @Test(expected = OBException.class) + public void testAddAdditionalParametersMissingRequiredParameter() throws Exception { + Map parameters = new HashMap<>(); + JSONObject jsonContent = new JSONObject(); + JSONObject params = new JSONObject(); + + jsonContent.put("_params", params); + + reportValuationStock.addAdditionalParameters(mockProcess, jsonContent, parameters); + } +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java new file mode 100644 index 000000000..4309d1908 --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java @@ -0,0 +1,221 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.erpCommon.utility.OBMessageUtils; +import org.openbravo.erpCommon.utility.Utility; +import org.openbravo.model.materialmgmt.cost.CostingAlgorithm; + +/** + * Unit tests for the {@link ReportValuationStock} class. + *

+ * This class validates the behavior of the {@code printReport} method, ensuring it correctly + * formats parameters, handles costing algorithms, and processes custom number formats. + *

+ */ + +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockPrintTest { + + @InjectMocks + private ReportValuationStock reportValuationStock; + + @Mock + private VariablesSecureApp vars; + + @Mock + private CostingAlgorithm costingAlgorithm; + + private Method printReportMethod; + private static final String TEST_DATE = "2024-01-01"; + private static final String TEST_COST_TYPE = "AVA"; + private static final String TEST_ALGORITHM_NAME = "Average Algorithm"; + private static final String TEST_TRANSLATED_HEADER = "Translated Cost Header"; + private static final String TEST_TRANSLATED_VALUATION = "Translated Valuation Header"; + + /** + * Sets up the test environment by initializing mocks and reflective access to the method under test. + * + * @throws Exception if the method cannot be accessed. + */ + + @Before + public void setUp() throws Exception { + printReportMethod = ReportValuationStock.class.getDeclaredMethod( + "printReport", + VariablesSecureApp.class, + String.class, + ReportValuationStockData[].class, + String.class, + CostingAlgorithm.class, + Map.class + ); + printReportMethod.setAccessible(true); + + when(vars.getSessionValue("#AD_ReportDecimalSeparator")).thenReturn("."); + when(vars.getSessionValue("#AD_ReportGroupingSeparator")).thenReturn(","); + when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn("#,##0.00"); + when(vars.getJavaDateFormat()).thenReturn("yyyy-MM-dd"); + + when(costingAlgorithm.getName()).thenReturn(TEST_ALGORITHM_NAME); + } + + /** + * Tests the {@code printReport} method with a defined costing algorithm. + *

+ * Validates that the method correctly processes headers and parameters + * when a costing algorithm is provided. + *

+ * + * @throws Exception if the method invocation fails. + */ + + @Test + public void testPrintReportWithCostingAlgorithm() throws Exception { + ReportValuationStockData[] testData = new ReportValuationStockData[0]; + Map parameters = new HashMap<>(); + DecimalFormat mockFormat = new DecimalFormat("#,##0.00"); + + try (MockedStatic obMessageUtilsMock = mockStatic(OBMessageUtils.class); + MockedStatic utilityMock = mockStatic(Utility.class)) { + + obMessageUtilsMock.when(() -> OBMessageUtils.messageBD("ValuedStockReport_CostHeader")) + .thenReturn("Cost Header @algorithm@"); + obMessageUtilsMock.when(() -> OBMessageUtils.messageBD("ValuedStockReport_ValuationHeader")) + .thenReturn("Valuation Header @algorithm@"); + obMessageUtilsMock.when(() -> OBMessageUtils.parseTranslation(anyString(), any())) + .thenReturn(TEST_TRANSLATED_HEADER) + .thenReturn(TEST_TRANSLATED_VALUATION); + + utilityMock.when(() -> Utility.getFormat(any(), anyString())).thenReturn(mockFormat); + + printReportMethod.invoke( + reportValuationStock, + vars, + TEST_DATE, + testData, + TEST_COST_TYPE, + costingAlgorithm, + parameters + ); + + assertNotNull("Parameters should not be null", parameters); + assertEquals("Should have correct cost header", + TEST_TRANSLATED_HEADER, parameters.get("ALG_COST")); + assertEquals("Should have correct valuation header", + TEST_TRANSLATED_VALUATION, parameters.get("SUM_ALG_COST")); + assertEquals("Should have correct title", + "Valued Stock Report", parameters.get("TITLE")); + assertEquals("Should have correct date", + TEST_DATE, parameters.get("DATE")); + assertNotNull("Should have number format", + parameters.get("NUMBERFORMAT")); + assertEquals("Should have correct decimal format", + mockFormat, parameters.get("COSTFORMAT")); + } + } + + /** + * Tests the {@code printReport} method without a costing algorithm. + *

+ * Confirms that the method correctly processes headers and parameters + * when no costing algorithm is provided. + *

+ * + * @throws Exception if the method invocation fails. + */ + + @Test + public void testPrintReportWithoutCostingAlgorithm() throws Exception { + ReportValuationStockData[] testData = new ReportValuationStockData[0]; + Map parameters = new HashMap<>(); + DecimalFormat mockFormat = new DecimalFormat("#,##0.00"); + + try (MockedStatic utilityMock = mockStatic(Utility.class)) { + utilityMock.when(() -> Utility.getFormat(any(), anyString())).thenReturn(mockFormat); + + printReportMethod.invoke( + reportValuationStock, + vars, + TEST_DATE, + testData, + null, + null, + parameters + ); + + assertNotNull("Parameters should not be null", parameters); + assertEquals("Should have empty cost header", + "", parameters.get("ALG_COST")); + assertEquals("Should have empty valuation header", + "", parameters.get("SUM_ALG_COST")); + assertEquals("Should have correct title", + "Valued Stock Report", parameters.get("TITLE")); + assertEquals("Should have correct date", + TEST_DATE, parameters.get("DATE")); + assertNotNull("Should have number format", + parameters.get("NUMBERFORMAT")); + assertEquals("Should have correct decimal format", + mockFormat, parameters.get("COSTFORMAT")); + } + } + + /** + * Tests the {@code printReport} method with custom number formats and separators. + *

+ * Ensures that the method correctly applies custom formatting settings for decimal + * and grouping separators. + *

+ * + * @throws Exception if the method invocation fails. + */ + + @Test + public void testPrintReportWithCustomFormats() throws Exception { + ReportValuationStockData[] testData = new ReportValuationStockData[0]; + Map parameters = new HashMap<>(); + DecimalFormat mockFormat = new DecimalFormat("#,##0.000"); + + when(vars.getSessionValue("#AD_ReportDecimalSeparator")).thenReturn(","); + when(vars.getSessionValue("#AD_ReportGroupingSeparator")).thenReturn("."); + when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn("#,##0.000"); + + try (MockedStatic utilityMock = mockStatic(Utility.class)) { + utilityMock.when(() -> Utility.getFormat(any(), anyString())).thenReturn(mockFormat); + + printReportMethod.invoke( + reportValuationStock, + vars, + TEST_DATE, + testData, + TEST_COST_TYPE, + null, + parameters + ); + + assertNotNull("Parameters should not be null", parameters); + assertNotNull("Should have number format with custom separators", + parameters.get("NUMBERFORMAT")); + assertEquals("Should have correct decimal format", + mockFormat, parameters.get("COSTFORMAT")); + } + } +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java new file mode 100644 index 000000000..98a35f93a --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java @@ -0,0 +1,174 @@ +package com.etendoerp.reportvaluationstock.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.data.FieldProvider; + +/** + * Unit tests for the {@link ReportValuationStock} class. + *

+ * This class validates the behavior of the {@code getSummaryProductCategories} method + * in various scenarios, including handling empty data, single category, multiple entries + * in the same category, and null costs. + *

+ */ + +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockSummaryTest { + + @InjectMocks + private ReportValuationStock reportValuationStock; + + private Method getSummaryProductCategoriesMethod; + + /** + * Sets up the test environment by initializing reflective access to the method under test. + * + * @throws Exception if the method cannot be accessed. + */ + + @Before + public void setUp() throws Exception { + getSummaryProductCategoriesMethod = ReportValuationStock.class.getDeclaredMethod( + "getSummaryProductCategories", + ReportValuationStockData[].class + ); + getSummaryProductCategoriesMethod.setAccessible(true); + } + + /** + * Sets the value of a field in the target object using reflection. + * + * @param target the target object whose field is to be modified + * @param fieldName the name of the field to set + * @param value the value to assign to the field + * @throws Exception if the field cannot be accessed or set + */ + + private void setFieldValue(Object target, String fieldName, Object value) throws Exception { + Field field = target.getClass().getField(fieldName); + field.set(target, value); + } + + /** + * Tests the {@code getSummaryProductCategories} method with empty input data. + *

+ * Ensures that the method returns an empty result when provided with no data. + *

+ * + * @throws Exception if the method invocation fails. + */ + + @Test + public void testGetSummaryProductCategoriesWithEmptyData() throws Exception { + ReportValuationStockData[] data = new ReportValuationStockData[0]; + + FieldProvider[] result = (FieldProvider[]) getSummaryProductCategoriesMethod.invoke( + reportValuationStock, + (Object) data + ); + + assertNotNull("Result should not be null", result); + assertEquals("Empty data should return empty result", 0, result.length); + } + + /** + * Tests the {@code getSummaryProductCategories} method with a single data entry. + *

+ * Validates that the method correctly processes and returns data for one category. + *

+ * + * @throws Exception if the method invocation fails. + */ + + @Test + public void testGetSummaryProductCategoriesWithSingleCategory() throws Exception { + ReportValuationStockData singleData = new ReportValuationStockData(); + setFieldValue(singleData, "categoryName", "TestCategory"); + setFieldValue(singleData, "totalCost", "100.00"); + + ReportValuationStockData[] data = new ReportValuationStockData[] { singleData }; + + FieldProvider[] result = (FieldProvider[]) getSummaryProductCategoriesMethod.invoke( + reportValuationStock, + (Object) data + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should contain one category", 1, result.length); + assertEquals("Should have correct category name", "TestCategory", + result[0].getField("category")); + assertEquals("Should have correct cost", "100.00", + result[0].getField("cost")); + } + + /** + * Tests the {@code getSummaryProductCategories} method with multiple entries in the same category. + *

+ * Verifies that the method aggregates costs correctly for a single category. + *

+ * + * @throws Exception if the method invocation fails. + */ + + @Test + public void testGetSummaryProductCategoriesWithMultipleEntriesSameCategory() throws Exception { + ReportValuationStockData data1 = new ReportValuationStockData(); + setFieldValue(data1, "categoryName", "TestCategory"); + setFieldValue(data1, "totalCost", "100.00"); + + ReportValuationStockData data2 = new ReportValuationStockData(); + setFieldValue(data2, "categoryName", "TestCategory"); + setFieldValue(data2, "totalCost", "50.00"); + + ReportValuationStockData[] data = new ReportValuationStockData[] { data1, data2 }; + + FieldProvider[] result = (FieldProvider[]) getSummaryProductCategoriesMethod.invoke( + reportValuationStock, + (Object) data + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should contain one category", 1, result.length); + assertEquals("Category name should match", "TestCategory", + result[0].getField("category")); + assertEquals("Total cost should be summed correctly", "150.00", + result[0].getField("cost")); + } + + /** + * Tests the {@code getSummaryProductCategories} method with null cost values. + *

+ * Confirms that the method handles null costs by treating them as zero. + *

+ * + * @throws Exception if the method invocation fails. + */ + + @Test + public void testGetSummaryProductCategoriesWithNullCosts() throws Exception { + ReportValuationStockData nullCostData = new ReportValuationStockData(); + setFieldValue(nullCostData, "categoryName", "TestCategory"); + setFieldValue(nullCostData, "totalCost", null); + + ReportValuationStockData[] data = new ReportValuationStockData[] { nullCostData }; + + FieldProvider[] result = (FieldProvider[]) getSummaryProductCategoriesMethod.invoke( + reportValuationStock, + (Object) data + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should contain one category", 1, result.length); + assertEquals("Cost should be zero for null values", "0", + result[0].getField("cost")); + } +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java new file mode 100644 index 000000000..d4ce4f53c --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java @@ -0,0 +1,165 @@ +package com.etendoerp.reportvaluationstock.handler; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.dal.core.OBContext; +import org.openbravo.dal.security.OrganizationStructureProvider; +import org.openbravo.dal.service.OBDal; +import org.hibernate.Session; +import org.hibernate.query.Query; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Unit tests for the {@link ReportValuationStock} class. + *

+ * This class validates the behavior of the {@code getWarehouses} method in various scenarios, + * including cases with results and cases with no results. + *

+ */ +@RunWith(MockitoJUnitRunner.class) +public class ReportValuationStockWarehousesTest { + + private static final String CLIENT_ID = "testClient"; + private static final String ORG_ID = "testOrg"; + private static final String WAREHOUSE_ID_1 = "warehouse1"; + private static final String WAREHOUSE_ID_2 = "warehouse2"; + + @InjectMocks + private ReportValuationStock reportValuationStock; + + @Mock + private OBDal mockOBDal; + + @Mock + private Session mockSession; + + @Mock + private Query mockQuery; + + @Mock + private OBContext mockOBContext; + + @Mock + private OrganizationStructureProvider mockOsp; + + private Method getWarehousesMethod; + + /** + * Sets up the test environment by initializing mocks and reflective access to the method under test. + * + * @throws Exception if the method cannot be accessed. + */ + @Before + public void setUp() throws Exception { + getWarehousesMethod = ReportValuationStock.class.getDeclaredMethod( + "getWarehouses", + String.class, + String.class + ); + getWarehousesMethod.setAccessible(true); + } + + /** + * Tests the {@code getWarehouses} method with valid inputs, expecting a non-empty list of results. + * + * @throws Exception if the method invocation fails. + */ + @Test + public void testGetWarehousesWithResults() throws Exception { + List expectedOrgIds = Arrays.asList("org1", "org2"); + List expectedWarehouseIds = Arrays.asList(WAREHOUSE_ID_1, WAREHOUSE_ID_2); + + try (MockedStatic obContextMock = mockStatic(OBContext.class); + MockedStatic obDalMock = mockStatic(OBDal.class)) { + + obContextMock.when(OBContext::getOBContext).thenReturn(mockOBContext); + when(mockOBContext.getOrganizationStructureProvider(CLIENT_ID)) + .thenReturn(mockOsp); + when(mockOsp.getNaturalTree(ORG_ID)) + .thenReturn(Set.copyOf(expectedOrgIds)); + + obDalMock.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); + when(mockOBDal.getSession()).thenReturn(mockSession); + when(mockSession.createQuery(anyString(), eq(String.class))) + .thenReturn(mockQuery); + when(mockQuery.setParameterList((String) eq("orgIds"), (Collection) any())) + .thenReturn(mockQuery); + when(mockQuery.setParameter(eq("clientId"), any())) + .thenReturn(mockQuery); + when(mockQuery.list()) + .thenReturn(expectedWarehouseIds); + + @SuppressWarnings("unchecked") + List result = (List) getWarehousesMethod.invoke( + reportValuationStock, + CLIENT_ID, + ORG_ID + ); + + assertEquals("Should return correct number of warehouses", + expectedWarehouseIds.size(), result.size()); + assertTrue("Should contain expected warehouse IDs", + result.containsAll(expectedWarehouseIds)); + } + } + + /** + * Tests the {@code getWarehouses} method with valid inputs, expecting an empty list when no results are found. + * + * @throws Exception if the method invocation fails. + */ + @Test + public void testGetWarehousesWithNoResults() throws Exception { + List expectedOrgIds = Arrays.asList("org1", "org2"); + List emptyWarehouseList = List.of(); + + try (MockedStatic obContextMock = mockStatic(OBContext.class); + MockedStatic obDalMock = mockStatic(OBDal.class)) { + + obContextMock.when(OBContext::getOBContext).thenReturn(mockOBContext); + when(mockOBContext.getOrganizationStructureProvider(CLIENT_ID)) + .thenReturn(mockOsp); + when(mockOsp.getNaturalTree(ORG_ID)) + .thenReturn(Set.copyOf(expectedOrgIds)); + + obDalMock.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); + when(mockOBDal.getSession()).thenReturn(mockSession); + when(mockSession.createQuery(anyString(), eq(String.class))) + .thenReturn(mockQuery); + when(mockQuery.setParameterList((String) eq("orgIds"), (Collection) any())) + .thenReturn(mockQuery); + when(mockQuery.setParameter(eq("clientId"), any())) + .thenReturn(mockQuery); + when(mockQuery.list()) + .thenReturn(emptyWarehouseList); + + @SuppressWarnings("unchecked") + List result = (List) getWarehousesMethod.invoke( + reportValuationStock, + CLIENT_ID, + ORG_ID + ); + + assertTrue("Should return empty list when no warehouses found", + result.isEmpty()); + } + } +} \ No newline at end of file From 2a0bf37e98915df29433f6041b38e0042ccc930c Mon Sep 17 00:00:00 2001 From: Emi-Polliotti Date: Mon, 16 Dec 2024 21:44:44 -0300 Subject: [PATCH 2/4] Feature ETP-870: Add unit tests for the jobs defaults module --- .../smf/jobs/defaults/CloneOrderHookTest.java | 244 +++++++++++ .../src/com/smf/jobs/defaults/PostTest.java | 219 ++++++++++ .../jobs/defaults/ProcessInvoicesTest.java | 298 +++++++++++++ .../defaults/ProcessOrdersDefaultsTest.java | 201 +++++++++ .../smf/jobs/defaults/ProcessOrdersTest.java | 183 ++++++++ .../jobs/defaults/ProcessShipmentTest.java | 406 ++++++++++++++++++ .../invoices/CreateFromOrderTest.java | 47 ++ .../CreateFromOrdersHQLTransformerTest.java | 102 +++++ .../defaults/offerPick/OfferAddOrgTest.java | 142 ++++++ .../OfferAddProductCategoryTest.java | 126 ++++++ .../offerPick/OfferAddProductTest.java | 183 ++++++++ .../provider/JobsComponentProviderTest.java | 121 ++++++ 12 files changed, 2272 insertions(+) create mode 100644 src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/PostTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java create mode 100644 src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java diff --git a/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java b/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java new file mode 100644 index 000000000..de57d080b --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java @@ -0,0 +1,244 @@ +package com.smf.jobs.defaults; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +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 java.lang.reflect.Method; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.query.Query; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.structure.BaseOBObject; +import org.openbravo.base.weld.WeldUtils; +import org.openbravo.dal.core.DalUtil; +import org.openbravo.dal.core.OBContext; +import org.openbravo.dal.service.OBDal; +import org.openbravo.dal.service.OBQuery; +import org.openbravo.erpCommon.businessUtility.CloneOrderHookCaller; +import org.openbravo.model.ad.access.User; +import org.openbravo.model.ad.system.Client; +import org.openbravo.model.common.enterprise.Organization; +import org.openbravo.model.common.order.Order; +import org.openbravo.model.common.order.OrderLine; +import org.openbravo.model.common.plm.Product; +import org.openbravo.model.pricing.pricelist.PriceList; +import org.openbravo.model.pricing.pricelist.PriceListVersion; +import org.openbravo.service.db.CallStoredProcedure; + +@RunWith(MockitoJUnitRunner.class) +public class CloneOrderHookTest { + + @InjectMocks + private CloneOrderHook cloneOrderHook; + + @Mock + private Order originalOrder; + + @Mock + private Order clonedOrder; + + @Mock + private User currentUser; + + @Mock + private OBDal obDal; + + @Mock + private Session session; + + @Mock + private OBContext obContext; + + @Mock + private OrderLine originalOrderLine; + + @Mock + private Product product; + + @Mock + private PriceList priceList; + + @Mock + private Client client; + + private MockedStatic mockedOBDal; + private MockedStatic mockedOBContext; + private MockedStatic mockedWeldUtils; + private MockedStatic mockedDalUtil; + private MockedStatic mockedCallStoredProcedure; + private Method cloneOrderMethod; + + @Before + public void setUp() throws Exception { + cloneOrderMethod = CloneOrderHook.class.getDeclaredMethod( + "cloneOrder", + User.class, + Order.class, + Order.class + ); + cloneOrderMethod.setAccessible(true); + + mockedOBDal = mockStatic(OBDal.class); + mockedOBContext = mockStatic(OBContext.class); + mockedWeldUtils = mockStatic(WeldUtils.class); + mockedDalUtil = mockStatic(DalUtil.class); + mockedCallStoredProcedure = mockStatic(CallStoredProcedure.class); + + mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); + mockedOBContext.when(OBContext::getOBContext).thenReturn(obContext); + when(obDal.getSession()).thenReturn(session); + } + + @Test + public void testCloneOrder() throws Exception { + // Setup organization + Organization organization = mock(Organization.class); + + // Setup order lines + List originalOrderLines = new ArrayList<>(); + originalOrderLines.add(originalOrderLine); + when(originalOrder.getOrderLineList()).thenReturn(originalOrderLines); + when(clonedOrder.getOrderLineList()).thenReturn(new ArrayList<>()); + + // Setup basic order configuration + when(originalOrder.getPriceList()).thenReturn(priceList); + when(originalOrder.getClient()).thenReturn(client); + when(originalOrder.isSalesTransaction()).thenReturn(true); + when(priceList.getId()).thenReturn("testPriceListId"); + when(client.getId()).thenReturn("testClientId"); + + // Setup order line details + when(originalOrderLine.getProduct()).thenReturn(product); + when(product.getId()).thenReturn("testProductId"); + when(originalOrderLine.getId()).thenReturn("testOrderLineId"); + when(originalOrderLine.getOrderlineServiceRelationList()).thenReturn(new ArrayList<>()); + + // Mock DalUtil copy + OrderLine clonedOrderLine = mock(OrderLine.class); + mockedDalUtil.when(() -> DalUtil.copy(any(OrderLine.class), eq(false))) + .thenReturn(clonedOrderLine); + + // Mock price list version query + OBQuery mockQuery = mock(OBQuery.class); + when(obDal.createQuery(eq(PriceListVersion.class), anyString())).thenReturn(mockQuery); + when(mockQuery.setNamedParameter(anyString(), any())).thenReturn(mockQuery); + when(mockQuery.list()).thenReturn(new ArrayList<>()); + + // Mock stored procedure call + CallStoredProcedure mockStoredProcedure = mock(CallStoredProcedure.class); + when(mockStoredProcedure.call(anyString(), any(), any())).thenReturn(BigDecimal.ONE); + mockedCallStoredProcedure.when(CallStoredProcedure::getInstance).thenReturn(mockStoredProcedure); + + // Mock CloneOrderHookCaller + CloneOrderHookCaller mockCaller = mock(CloneOrderHookCaller.class); + mockedWeldUtils.when(() -> WeldUtils.getInstanceFromStaticBeanManager(CloneOrderHookCaller.class)) + .thenReturn(mockCaller); + doNothing().when(mockCaller).executeHook(any(Order.class)); + + // Execute test + Order result = (Order) cloneOrderMethod.invoke(cloneOrderHook, currentUser, originalOrder, clonedOrder); + + // Verify results + assertNotNull("Cloned order should not be null", result); + + // Verify the basic order properties + verify(clonedOrder).setDocumentAction("CO"); + verify(clonedOrder).setDocumentStatus("DR"); + verify(clonedOrder).setPosted("N"); + verify(clonedOrder).setProcessed(false); + verify(clonedOrder).setDelivered(false); + verify(clonedOrder, times(2)).setSalesTransaction(anyBoolean()); // Allow 2 calls + verify(clonedOrder).setDocumentNo(null); + verify(clonedOrder).setCreatedBy(currentUser); + verify(clonedOrder).setUpdatedBy(currentUser); + verify(clonedOrder).setGrandTotalAmount(BigDecimal.ZERO); + verify(clonedOrder).setSummedLineAmount(BigDecimal.ZERO); + + // Verify DAL operations + verify(obDal).save(clonedOrder); + verify(obDal).flush(); + verify(obDal).refresh(clonedOrder); + + // Verify order line operations + verify(clonedOrderLine).setSalesOrder(clonedOrder); + verify(clonedOrderLine).setReservedQuantity(BigDecimal.ZERO); + verify(clonedOrderLine).setDeliveredQuantity(BigDecimal.ZERO); + verify(clonedOrderLine).setInvoicedQuantity(BigDecimal.ZERO); + } + + @Test + public void testGetLineNetAmt() { + String testOrderId = "test-order-id"; + BigDecimal expectedAmount = new BigDecimal("100.00"); + List amounts = new ArrayList<>(); + amounts.add(expectedAmount); + + @SuppressWarnings("unchecked") + Query mockQuery = mock(Query.class); + when(session.createQuery(anyString(), eq(BigDecimal.class))).thenReturn(mockQuery); + when(mockQuery.setParameter(anyString(), anyString())).thenReturn(mockQuery); + when(mockQuery.list()).thenReturn(amounts); + + BigDecimal result = CloneOrderHook.getLineNetAmt(testOrderId); + + assertEquals("Line net amount should match expected value", expectedAmount, result); + verify(mockQuery).setParameter("orderId", testOrderId); + } + + @Test + public void testShouldCopyChildren() { + boolean result = cloneOrderHook.shouldCopyChildren(true); + assertEquals("Should always return false regardless of input", false, result); + } + + @Test + public void testPreCopy() { + BaseOBObject result = cloneOrderHook.preCopy(originalOrder); + assertEquals("Should return original record without modification", originalOrder, result); + } + + @After + public void tearDown() { + if (mockedOBDal != null) { + mockedOBDal.close(); + System.out.println("mockedOBDal cerrado correctamente."); + } + if (mockedOBContext != null) { + mockedOBContext.close(); + System.out.println("mockedOBContext cerrado correctamente."); + } + if (mockedWeldUtils != null) { + mockedWeldUtils.close(); + System.out.println("mockedWeldUtils cerrado correctamente."); + } + if (mockedDalUtil != null) { + mockedDalUtil.close(); + System.out.println("mockedDalUtil cerrado correctamente."); + } + if (mockedCallStoredProcedure != null) { + mockedCallStoredProcedure.close(); + System.out.println("mockedCallStoredProcedure cerrado correctamente."); + } + } + +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/PostTest.java b/src-test/src/com/smf/jobs/defaults/PostTest.java new file mode 100644 index 000000000..16ae525d1 --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/PostTest.java @@ -0,0 +1,219 @@ +package com.smf.jobs.defaults; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.mutable.MutableBoolean; +import org.codehaus.jettison.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.model.Entity; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.base.structure.BaseOBObject; +import org.openbravo.client.kernel.RequestContext; +import org.openbravo.dal.service.OBDal; +import org.openbravo.erpCommon.ad_actionButton.ActionButtonUtility; +import org.openbravo.erpCommon.utility.OBError; +import org.openbravo.erpCommon.utility.OBMessageUtils; +import org.openbravo.model.ad.system.Client; +import org.openbravo.model.common.enterprise.Organization; +import org.openbravo.service.db.DalConnectionProvider; + +import com.smf.jobs.ActionResult; +import com.smf.jobs.Result; + +@RunWith(MockitoJUnitRunner.class) +public class PostTest { + + @Spy + private Post post; + + @Mock + private OBDal obDal; + + @Mock + private RequestContext requestContext; + @Mock + private VariablesSecureApp vars; + @Mock + private BaseOBObject mockRecord; + @Mock + private Organization organization; + @Mock + private Client client; + @Mock + private Entity entity; + + @Before + public void setUp() { + + when(organization.getId()).thenReturn("testOrgId"); + when(entity.getTableId()).thenReturn("318"); + + when(mockRecord.getId()).thenReturn("testId"); + when(mockRecord.getEntity()).thenReturn(entity); + when(mockRecord.get("organization")).thenReturn(organization); + when(mockRecord.get("client")).thenReturn(client); + + } + + @Test + public void testActionWithMultipleSuccessfulPostings() throws Exception { + JSONObject parameters = new JSONObject(); + MutableBoolean isStopped = new MutableBoolean(false); + + BaseOBObject mockRecord2 = mock(BaseOBObject.class); + when(mockRecord2.getId()).thenReturn("testId2"); + when(mockRecord2.get("posted")).thenReturn("N"); + when(mockRecord2.getEntity()).thenReturn(entity); + when(mockRecord2.get("organization")).thenReturn(organization); + when(mockRecord2.get("client")).thenReturn(client); + + List records = Arrays.asList(mockRecord, mockRecord2); + + OBError successResult = new OBError(); + successResult.setType("Success"); + successResult.setMessage("Posted successfully"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class); + MockedStatic obDalMock = mockStatic(OBDal.class); + MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(requestContext); + when(requestContext.getVariablesSecureApp()).thenReturn(vars); + obDalMock.when(OBDal::getInstance).thenReturn(obDal); + + actionButtonUtilityMock.when(() -> ActionButtonUtility.processButton( + any(VariablesSecureApp.class), + anyString(), + anyString(), + anyString(), + any(DalConnectionProvider.class) + )).thenReturn(successResult); + + messageMock.when(() -> OBMessageUtils.messageBD(anyString())).thenReturn("DJOBS_PostUnpostMessage"); + doReturn(records).when(post).getInputContents(any()); + + ActionResult result = post.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + verify(mockRecord, times(1)).getId(); + verify(mockRecord2, times(1)).getId(); + } + } + + @Test + public void testActionWithMixedResults() throws Exception { + JSONObject parameters = new JSONObject(); + MutableBoolean isStopped = new MutableBoolean(false); + + BaseOBObject mockRecord2 = mock(BaseOBObject.class); + when(mockRecord2.getId()).thenReturn("testId2"); + when(mockRecord2.get("posted")).thenReturn("N"); + when(mockRecord2.getEntity()).thenReturn(entity); + when(mockRecord2.get("organization")).thenReturn(organization); + when(mockRecord2.get("client")).thenReturn(client); + + List records = Arrays.asList(mockRecord, mockRecord2); + + OBError successResult = new OBError(); + successResult.setType("Success"); + OBError errorResult = new OBError(); + errorResult.setType("Error"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class); + MockedStatic obDalMock = mockStatic(OBDal.class); + MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(requestContext); + when(requestContext.getVariablesSecureApp()).thenReturn(vars); + obDalMock.when(OBDal::getInstance).thenReturn(obDal); + + actionButtonUtilityMock.when(() -> ActionButtonUtility.processButton( + any(VariablesSecureApp.class), + eq("testId"), + anyString(), + anyString(), + any(DalConnectionProvider.class) + )).thenReturn(successResult); + + actionButtonUtilityMock.when(() -> ActionButtonUtility.processButton( + any(VariablesSecureApp.class), + eq("testId2"), + anyString(), + anyString(), + any(DalConnectionProvider.class) + )).thenReturn(errorResult); + + messageMock.when(() -> OBMessageUtils.messageBD(anyString())).thenReturn("DJOBS_PostUnpostMessage"); + doReturn(records).when(post).getInputContents(any()); + + ActionResult result = post.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return warning type for mixed results", Result.Type.WARNING, result.getType()); + } + } + + @Test + public void testActionWithEmptyRecordList() throws Exception { + JSONObject parameters = new JSONObject(); + MutableBoolean isStopped = new MutableBoolean(false); + List records = Collections.emptyList(); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic obDalMock = mockStatic(OBDal.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(requestContext); + when(requestContext.getVariablesSecureApp()).thenReturn(vars); + obDalMock.when(OBDal::getInstance).thenReturn(obDal); + + doReturn(records).when(post).getInputContents(any()); + + ActionResult result = post.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type for empty list", Result.Type.SUCCESS, result.getType()); + } + } + + + @Test + public void testActionWithException() throws Exception { + JSONObject parameters = new JSONObject(); + MutableBoolean isStopped = new MutableBoolean(false); + List records = Collections.singletonList(mockRecord); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic obDalMock = mockStatic(OBDal.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(requestContext); + when(requestContext.getVariablesSecureApp()).thenReturn(vars); + obDalMock.when(OBDal::getInstance).thenReturn(obDal); + + doReturn(records).when(post).getInputContents(any()); + doThrow(new RuntimeException("Test exception")).when(mockRecord).get("posted"); + + ActionResult result = post.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return error type", Result.Type.ERROR, result.getType()); + assertEquals("Should return exception message", "Test exception", result.getMessage()); + } + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java b/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java new file mode 100644 index 000000000..01cb3a7bf --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java @@ -0,0 +1,298 @@ +package com.smf.jobs.defaults; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +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 java.lang.reflect.Method; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.mutable.MutableBoolean; +import org.codehaus.jettison.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.advpaymentmngt.ProcessInvoiceUtil; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.base.weld.WeldUtils; +import org.openbravo.client.kernel.RequestContext; +import org.openbravo.dal.service.OBDal; +import org.openbravo.erpCommon.utility.OBDateUtils; +import org.openbravo.erpCommon.utility.OBError; +import org.openbravo.model.common.invoice.Invoice; +import org.openbravo.service.db.DalConnectionProvider; +import org.openbravo.service.json.JsonUtils; + +import com.smf.jobs.ActionResult; +import com.smf.jobs.Result; +import com.smf.jobs.Data; + +/** + * Unit tests for the ProcessInvoices class. + * This class contains tests to validate the behavior of processing invoices + * in various scenarios, such as handling void dates, verifying successful + * processing, and ensuring proper pre-run setup. + * + * It uses JUnit and Mockito for testing and mocking dependencies. + */ +@RunWith(MockitoJUnitRunner.class) +public class ProcessInvoicesTest { + + @Spy + @InjectMocks + private TestableProcessInvoices processInvoices; + + @Mock + private WeldUtils mockWeldUtils; + + @Mock + private ProcessInvoiceUtil mockProcessInvoiceUtil; + + @Mock + private RequestContext mockRequestContext; + + @Mock + private VariablesSecureApp mockVars; + + @Mock + private Invoice mockInvoice; + + @Mock + private OBDal mockOBDal; + + @Mock + private Data mockData; + + private Method processInvoiceMethod; + + /** + * Sets up the test environment, including retrieving the private method + * "processInvoice" from the ProcessInvoices class for invocation in tests. + * + * @throws Exception if the method cannot be accessed or found. + */ + @Before + public void setUp() throws Exception { + processInvoiceMethod = ProcessInvoices.class.getDeclaredMethod( + "processInvoice", + Invoice.class, + String.class, + String.class, + String.class + ); + processInvoiceMethod.setAccessible(true); + } + + /** + * Tests the processInvoice method when void dates are not provided. + * Validates that the invoice is processed successfully with the provided + * document action. + * + * @throws Exception if the method invocation fails. + */ + @Test + public void testProcessInvoiceWithoutVoidDates() throws Exception { + String invoiceId = "test-invoice-id"; + String docAction = "CO"; + OBError expectedResult = new OBError(); + expectedResult.setType("Success"); + expectedResult.setMessage("Invoice processed successfully"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)).thenReturn(mockProcessInvoiceUtil); + when(mockInvoice.getId()).thenReturn(invoiceId); + when(mockProcessInvoiceUtil.process( + eq(invoiceId), + eq(docAction), + eq(""), + eq(""), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(expectedResult); + + OBError result = (OBError) processInvoiceMethod.invoke( + processInvoices, + mockInvoice, + docAction, + null, + null + ); + + assertEquals("Should return success type", "Success", result.getType()); + assertEquals("Should return correct message", "Invoice processed successfully", result.getMessage()); + } + } + + /** + * Tests the processInvoice method when void dates are provided. + * Validates that the invoice is processed successfully and formatted + * dates are passed to the process method. + * + * @throws Exception if the method invocation fails. + */ + @Test + public void testProcessInvoiceWithVoidDates() throws Exception { + String invoiceId = "test-invoice-id"; + String docAction = "VO"; + String voidDate = "2024-01-15"; + String voidAcctDate = "2024-01-15"; + + OBError expectedResult = new OBError(); + expectedResult.setType("Success"); + + SimpleDateFormat jsonDateFormat = JsonUtils.createDateFormat(); + Date testDate = jsonDateFormat.parse(voidDate); + String formattedDate = OBDateUtils.formatDate(testDate); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)).thenReturn(mockProcessInvoiceUtil); + when(mockInvoice.getId()).thenReturn(invoiceId); + when(mockProcessInvoiceUtil.process( + eq(invoiceId), + eq(docAction), + eq(formattedDate), + eq(formattedDate), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(expectedResult); + + OBError result = (OBError) processInvoiceMethod.invoke( + processInvoices, + mockInvoice, + docAction, + voidDate, + voidAcctDate + ); + + assertEquals("Should return success type", "Success", result.getType()); + } + } + + /** + * Tests the action method to ensure it correctly handles processing invoices + * when the processing result is successful. + * + * @throws Exception if the action execution fails. + */ + @Test + public void testActionWithSuccessfulProcessing() throws Exception { + JSONObject parameters = new JSONObject(); + parameters.put("DocAction", "CO"); + MutableBoolean isStopped = new MutableBoolean(false); + + List mockInvoices = List.of(mockInvoice); + OBError successResult = new OBError(); + successResult.setType("Success"); + + doReturn(mockInvoices).when(processInvoices).getInputContents(any()); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)).thenReturn(mockProcessInvoiceUtil); + when(mockInvoice.getId()).thenReturn("testId"); + when(mockProcessInvoiceUtil.process( + anyString(), + anyString(), + anyString(), + anyString(), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(successResult); + + ActionResult result = processInvoices.action(parameters, isStopped); + + assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + } + } + + /** + * Tests the preRun method to verify that invoices with the "process now" + * flag are properly locked, updated, and saved before processing. + * + * @throws Exception if the preRun setup or execution fails. + */ + @Test + public void testPreRunWithLockedInvoice() throws Exception { + JSONObject jsonContent = new JSONObject(); + JSONObject params = new JSONObject(); + params.put("DocAction", "CO"); + jsonContent.put("_params", params); + + List mockInvoices = List.of(mockInvoice); + OBError successResult = new OBError(); + successResult.setType("Success"); + + try (MockedStatic obDalMock = mockStatic(OBDal.class); + MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + + obDalMock.when(OBDal::getInstance).thenReturn(mockOBDal); + doNothing().when(mockOBDal).save(any()); + doNothing().when(mockOBDal).flush(); + + doReturn(mockInvoices).when(processInvoices).getInputContents(any()); + doReturn(mockData).when(processInvoices).getInput(); + + when(mockInvoice.isProcessNow()).thenReturn(true); + when(mockInvoice.getId()).thenReturn("testId"); + + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)).thenReturn(mockProcessInvoiceUtil); + when(mockProcessInvoiceUtil.process( + anyString(), + eq("XL"), + anyString(), + anyString(), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(successResult); + + Data result = processInvoices.preRun(jsonContent); + + assertNotNull("Result should not be null", result); + verify(mockInvoice, times(1)).setAPRMProcessinvoice("--"); + verify(mockOBDal, times(1)).save(mockInvoice); + verify(mockOBDal, times(1)).flush(); + } + } + + /** + * A testable subclass of ProcessInvoices that exposes certain protected + * or private methods for testing purposes. + */ + public static class TestableProcessInvoices extends ProcessInvoices { + @Override + public Data getInput() { + return super.getInput(); + } + } + + /** + * Verifies that the getInputClass method returns the correct input class + * for processing invoices. + */ + @Test + public void testGetInputClass() { + assertEquals("Should return Invoice.class", Invoice.class, processInvoices.getInputClass()); + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java b/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java new file mode 100644 index 000000000..1d115213e --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java @@ -0,0 +1,201 @@ +package com.smf.jobs.defaults; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.client.kernel.RequestContext; +import org.openbravo.data.FieldProvider; +import org.openbravo.erpCommon.ad_actionButton.ActionButtonUtility; +import org.openbravo.service.db.DalConnectionProvider; + +/** + * Unit test class for {@link ProcessOrdersDefaults}. + * This class verifies the behavior of methods in the ProcessOrdersDefaults class. + */ +@RunWith(MockitoJUnitRunner.class) +public class ProcessOrdersDefaultsTest { + + @InjectMocks + private ProcessOrdersDefaults processOrdersDefaults; + + @Mock + private RequestContext mockRequestContext; + + @Mock + private VariablesSecureApp mockVars; + + @Mock + private DalConnectionProvider mockConnectionProvider; + + /** + * Sets up the test environment before each test case. + * Initializes common mocks and variables required across tests. + */ + @Before + public void setUp() { + // Common setup if needed + } + + /** + * Sets up the test environment before each test case. + * Initializes common mocks and variables required across tests. + */ + @Test + public void testExecuteWithSingleDocumentStatus() throws Exception { + Map parameters = new HashMap<>(); + String content = new JSONObject() + .put("documentStatuses", new JSONArray().put("DR")) + .put("isProcessing", "N") + .put("tabId", "123") + .toString(); + + FieldProvider mockFieldProvider = mock(FieldProvider.class); + when(mockFieldProvider.getField("ID")).thenReturn("CO"); + FieldProvider[] mockFields = new FieldProvider[]{mockFieldProvider}; + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + + actionButtonUtilityMock.when(() -> ActionButtonUtility.docAction( + any(), + any(), + anyString(), + eq(ProcessOrdersDefaults.ORDER_DOCUMENT_ACTION_REFERENCE_ID), + eq("DR"), + eq("N"), + eq(ProcessOrdersDefaults.AD_TABLE_ID), + eq("123") + )).thenReturn(mockFields); + + JSONObject result = processOrdersDefaults.execute(parameters, content); + + assertNotNull("Result should not be null", result); + assertTrue("Result should contain actions", result.has("actions")); + JSONArray actions = result.getJSONArray("actions"); + assertEquals("Should have one action", 1, actions.length()); + assertEquals("Should have correct action", "CO", actions.getString(0)); + } + } + + /** + * Tests the {@link ProcessOrdersDefaults#execute(Map, String)} method when there are multiple document statuses. + * Verifies the result structure and correctness of returned actions. + * + * @throws Exception if an error occurs during test execution + */ + @Test + public void testExecuteWithMultipleDocumentStatuses() throws Exception { + Map parameters = new HashMap<>(); + String content = new JSONObject() + .put("documentStatuses", new JSONArray().put("DR").put("CO")) + .put("isProcessing", "N") + .put("tabId", "123") + .toString(); + + FieldProvider mockFieldProvider1 = mock(FieldProvider.class); + FieldProvider mockFieldProvider2 = mock(FieldProvider.class); + when(mockFieldProvider1.getField("ID")).thenReturn("CO"); + when(mockFieldProvider2.getField("ID")).thenReturn("CL"); + + FieldProvider[] mockFields1 = new FieldProvider[]{mockFieldProvider1}; + FieldProvider[] mockFields2 = new FieldProvider[]{mockFieldProvider2}; + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + + actionButtonUtilityMock.when(() -> ActionButtonUtility.docAction( + any(), + any(), + anyString(), + eq(ProcessOrdersDefaults.ORDER_DOCUMENT_ACTION_REFERENCE_ID), + eq("DR"), + eq("N"), + eq(ProcessOrdersDefaults.AD_TABLE_ID), + eq("123") + )).thenReturn(mockFields1); + + actionButtonUtilityMock.when(() -> ActionButtonUtility.docAction( + any(), + any(), + anyString(), + eq(ProcessOrdersDefaults.ORDER_DOCUMENT_ACTION_REFERENCE_ID), + eq("CO"), + eq("N"), + eq(ProcessOrdersDefaults.AD_TABLE_ID), + eq("123") + )).thenReturn(mockFields2); + + JSONObject result = processOrdersDefaults.execute(parameters, content); + + assertNotNull("Result should not be null", result); + assertTrue("Result should contain actions", result.has("actions")); + JSONArray actions = result.getJSONArray("actions"); + assertEquals("Should have two actions", 2, actions.length()); + assertEquals("First action should be CO", "CO", actions.getString(0)); + assertEquals("Second action should be CL", "CL", actions.getString(1)); + } + } + + /** + * Tests the {@link ProcessOrdersDefaults(String, String, String, VariablesSecureApp, DalConnectionProvider)} + * method to ensure it correctly retrieves document actions based on input parameters. + */ + @Test + public void testGetDocumentActionList() { + FieldProvider mockFieldProvider = mock(FieldProvider.class); + when(mockFieldProvider.getField("ID")).thenReturn("CO"); + FieldProvider[] mockFields = new FieldProvider[]{mockFieldProvider}; + + try (MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class)) { + actionButtonUtilityMock.when(() -> ActionButtonUtility.docAction( + any(), + any(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString() + )).thenReturn(mockFields); + + List result = ProcessOrdersDefaults.getDocumentActionList( + "DR", + "N", + "123", + mockVars, + mockConnectionProvider + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should have one action", 1, result.size()); + assertEquals("Should have correct action", "CO", result.get(0)); + } + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java b/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java new file mode 100644 index 000000000..072e1cc22 --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java @@ -0,0 +1,183 @@ +package com.smf.jobs.defaults; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doReturn; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang.mutable.MutableBoolean; +import org.codehaus.jettison.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.advpaymentmngt.ProcessOrderUtil; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.base.weld.WeldUtils; +import org.openbravo.client.kernel.RequestContext; +import org.openbravo.erpCommon.utility.OBError; +import org.openbravo.model.common.order.Order; +import org.openbravo.service.db.DalConnectionProvider; + +import com.smf.jobs.ActionResult; +import com.smf.jobs.Result; + +/** + * Unit tests for the {@code ProcessOrders} class. + * Verifies the functionality for processing orders, including: + * - Reflection-based tests for private methods. + * - Handling of successful and erroneous scenarios during order processing. + */ +@RunWith(MockitoJUnitRunner.class) +public class ProcessOrdersTest { + + @Spy + @InjectMocks + private ProcessOrders processOrders; + + @Mock + private WeldUtils mockWeldUtils; + + @Mock + private ProcessOrderUtil mockOrderUtil; + + @Mock + private RequestContext mockRequestContext; + + @Mock + private VariablesSecureApp mockVars; + + @Mock + private Order mockOrder; + + private Method processOrderMethod; + + /** + * Sets up the test environment, initializing mock dependencies and + * preparing the {@code processOrder} method for reflection-based testing. + * + * @throws Exception If setup fails or reflection setup encounters issues. + */ + @Before + public void setUp() throws Exception { + processOrderMethod = ProcessOrders.class.getDeclaredMethod( + "processOrder", + Order.class, + String.class + ); + processOrderMethod.setAccessible(true); + } + + /** + * Tests the {@code processOrder} private method using reflection to ensure + * an order is successfully processed and the correct result is returned. + * + * @throws Exception If invocation of the private method fails. + */ + @Test + public void testProcessOrder() throws Exception { + String orderId = "test-order-id"; + String docAction = "CO"; + OBError expectedResult = new OBError(); + expectedResult.setType("Success"); + expectedResult.setMessage("Order processed successfully"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessOrderUtil.class)).thenReturn(mockOrderUtil); + when(mockOrder.getId()).thenReturn(orderId); + when(mockOrderUtil.process( + eq(orderId), + eq(docAction), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(expectedResult); + + OBError result = (OBError) processOrderMethod.invoke( + processOrders, + mockOrder, + docAction + ); + + assertEquals("Should return success type", "Success", result.getType()); + assertEquals( + "Should return correct message", + "Order processed successfully", + result.getMessage() + ); + } + } + + /** + * Verifies the successful execution of the {@code action} method when + * valid orders and parameters are provided. + * + * @throws Exception If the processing fails unexpectedly. + */ + @Test + public void testActionWithSuccessfulProcessing() throws Exception { + JSONObject parameters = new JSONObject(); + parameters.put("DocAction", "CO"); + MutableBoolean isStopped = new MutableBoolean(false); + + List mockOrders = Arrays.asList(mockOrder); + OBError successResult = new OBError(); + successResult.setType("Success"); + + doReturn(mockOrders).when(processOrders).getInputContents(any()); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessOrderUtil.class)).thenReturn(mockOrderUtil); + when(mockOrder.getId()).thenReturn("testId"); + when(mockOrderUtil.process( + anyString(), + anyString(), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(successResult); + + ActionResult result = processOrders.action(parameters, isStopped); + + assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + } + } + + /** + * Tests the {@code action} method to ensure it correctly handles a scenario + * where no valid input orders are provided, returning an error result. + */ + @Test + public void testActionWithError() { + JSONObject parameters = new JSONObject(); + MutableBoolean isStopped = new MutableBoolean(false); + + doReturn(List.of()).when(processOrders).getInputContents(any()); + + ActionResult result = processOrders.action(parameters, isStopped); + + assertEquals("Should return error type", Result.Type.ERROR, result.getType()); + } + + /** + * Validates the correct input class type returned by the {@code getInputClass} method. + * Ensures it matches the expected {@code Order.class} type. + */ + @Test + public void testGetInputClass() { + assertEquals("Should return Order.class", Order.class, processOrders.getInputClass()); + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java b/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java new file mode 100644 index 000000000..b5873119e --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java @@ -0,0 +1,406 @@ +package com.smf.jobs.defaults; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +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 java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.mutable.MutableBoolean; +import org.codehaus.jettison.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.advpaymentmngt.ProcessShipmentUtil; +import org.openbravo.base.secureApp.VariablesSecureApp; +import org.openbravo.base.weld.WeldUtils; +import org.openbravo.client.kernel.RequestContext; +import org.openbravo.erpCommon.utility.OBError; +import org.openbravo.erpCommon.utility.OBMessageUtils; +import org.openbravo.model.materialmgmt.transaction.ShipmentInOut; +import org.openbravo.service.db.DalConnectionProvider; + +import com.smf.jobs.ActionResult; +import com.smf.jobs.Data; +import com.smf.jobs.Result; + +/** + * Unit tests for the {@code ProcessShipment} class. + * Tests functionality related to shipment processing, covering: + * - Private methods using reflection. + * - Actions with successful and error outcomes. + * - Handling of invalid or edge-case inputs. + */ +@RunWith(MockitoJUnitRunner.Silent.class) +public class ProcessShipmentTest { + + /** + * A testable subclass of {@code ProcessShipment} that exposes methods for testing. + */ + public static class TestableProcessShipment extends ProcessShipment { + + /** + * Overrides the {@code getInput} method to expose it for testing. + * @return Data object representing the input for shipment processing. + */ + @Override + public Data getInput() { + return super.getInput(); + } + } + + @Spy + @InjectMocks + private TestableProcessShipment processShipment; + + @Mock + private WeldUtils mockWeldUtils; + + @Mock + private ProcessShipmentUtil mockProcessShipmentUtil; + + @Mock + private RequestContext mockRequestContext; + + @Mock + private VariablesSecureApp mockVars; + + @Mock + private ShipmentInOut mockShipment; + + @Mock + private Data mockData; + + private Method processShipmentMethod; + + /** + * Initializes test dependencies and configurations, such as static mocks + * for utility methods and reflection access to private methods. + * @throws Exception If setup fails. + */ + @Before + public void setUp() throws Exception { + processShipmentMethod = ProcessShipment.class.getDeclaredMethod( + "processShipment", + ShipmentInOut.class, + String.class + ); + processShipmentMethod.setAccessible(true); + + try (MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { + messageMock.when(() -> OBMessageUtils.messageBD(anyString())) + .thenReturn("Test message"); + messageMock.when(() -> OBMessageUtils.parseTranslation(anyString(), any())) + .thenReturn("Test message"); + } + + } + + /** + * Tests the {@code processShipment} private method to ensure it processes + * a shipment with valid data and returns a successful result. + * @throws Exception If invocation of the private method fails. + */ + @Test + public void testProcessShipmentPrivateMethod() throws Exception { + String shipmentId = "test-shipment-id"; + String docAction = "CO"; + OBError expectedResult = new OBError(); + expectedResult.setType("Success"); + expectedResult.setMessage("Shipment processed successfully"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessShipmentUtil.class)).thenReturn(mockProcessShipmentUtil); + when(mockShipment.getId()).thenReturn(shipmentId); + when(mockProcessShipmentUtil.process( + eq(shipmentId), + eq(docAction), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(expectedResult); + + OBError result = (OBError) processShipmentMethod.invoke( + processShipment, + mockShipment, + docAction + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type", "Success", result.getType()); + assertEquals( + "Should return correct message", + "Shipment processed successfully", + result.getMessage() + ); + } + } + + /** + * Verifies the successful execution of the {@code action} method when + * valid shipments and parameters are provided. + * @throws Exception If processing fails unexpectedly. + */ + @Test + public void testActionWithSuccessfulProcessing() throws Exception { + JSONObject parameters = new JSONObject(); + parameters.put("DocAction", "CO"); + MutableBoolean isStopped = new MutableBoolean(false); + + List mockShipments = List.of(mockShipment); + OBError successResult = new OBError(); + successResult.setType("Success"); + successResult.setMessage("Shipment processed successfully"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessShipmentUtil.class)).thenReturn(mockProcessShipmentUtil); + when(mockShipment.getId()).thenReturn("testId"); + when(mockProcessShipmentUtil.process( + anyString(), + anyString(), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(successResult); + + doReturn(mockShipments).when(processShipment).getInputContents(any()); + doReturn(mockData).when(processShipment).getInput(); + + ActionResult result = processShipment.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + verify(mockProcessShipmentUtil, times(1)).process( + anyString(), + anyString(), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + ); + } + } + + /** + * Tests the {@code action} method to ensure it handles errors appropriately + * when an unexpected condition occurs during shipment processing. + */ + @Test + public void testActionWithError() { + JSONObject parameters = new JSONObject(); + MutableBoolean isStopped = new MutableBoolean(false); + + List mockShipments = List.of(mockShipment); + + doReturn(mockShipments).when(processShipment).getInputContents(any()); + + ActionResult result = processShipment.action(parameters, isStopped); + + assertEquals("Should return error type", Result.Type.ERROR, result.getType()); + } + + /** + * Checks that the {@code action} method can handle cases where input is empty, + * returning a successful result without performing any actions. + * @throws Exception If processing fails. + */ + @Test + public void testActionWithEmptyInput() throws Exception { + JSONObject parameters = new JSONObject(); + parameters.put("DocAction", "CO"); + MutableBoolean isStopped = new MutableBoolean(false); + + List emptyShipments = Collections.emptyList(); + doReturn(emptyShipments).when(processShipment).getInputContents(any()); + doReturn(mockData).when(processShipment).getInput(); + + ActionResult result = processShipment.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type for empty input", Result.Type.SUCCESS, result.getType()); + } + + /** + * Tests the {@code processShipment} private method to ensure it processes + * a valid shipment and returns an OBError with the expected success result. + * Validates that the returned OBError contains the correct type and message. + * + * @throws Exception If invocation of the private method fails or an unexpected exception occurs. + */ + @Test + public void testProcessShipment() throws Exception { + String shipmentId = "test-shipment-id"; + String docAction = "CO"; + OBError expectedResult = new OBError(); + expectedResult.setType("Success"); + expectedResult.setMessage("Shipment processed successfully"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessShipmentUtil.class)).thenReturn(mockProcessShipmentUtil); + when(mockShipment.getId()).thenReturn(shipmentId); + when(mockProcessShipmentUtil.process( + eq(shipmentId), + eq(docAction), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(expectedResult); + + OBError result = (OBError) processShipmentMethod.invoke( + processShipment, + mockShipment, + docAction + ); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type", "Success", result.getType()); + } + } + + /** + * Validates the {@code processShipment} private method when the input shipment is null, + * ensuring a {@code NullPointerException} is thrown as expected. + * @throws Exception If invocation fails. + */ + @Test + public void testProcessShipmentWithNullShipment() throws Exception { + try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + + try { + processShipmentMethod.invoke(processShipment, null, "CO"); + fail("Should throw NullPointerException"); + } catch (InvocationTargetException e) { + assertTrue(e.getCause() instanceof NullPointerException); + } + } + } + + /** + * Ensures the {@code action} method identifies and handles invalid document actions, + * returning an appropriate error result. + * @throws Exception If an unexpected exception occurs. + */ + @Test + public void testActionWithInvalidDocAction() throws Exception { + JSONObject parameters = new JSONObject(); + parameters.put("DocAction", "INVALID_ACTION"); + MutableBoolean isStopped = new MutableBoolean(false); + + List mockShipments = List.of(mockShipment); + OBError errorResult = new OBError(); + errorResult.setType("Error"); + errorResult.setMessage("Invalid document action"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessShipmentUtil.class)).thenReturn(mockProcessShipmentUtil); + when(mockShipment.getId()).thenReturn("testId"); + when(mockProcessShipmentUtil.process( + anyString(), + eq("INVALID_ACTION"), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(errorResult); + + messageMock.when(() -> OBMessageUtils.messageBD(anyString())) + .thenReturn("Test message"); + + doReturn(mockShipments).when(processShipment).getInputContents(any()); + doReturn(mockData).when(processShipment).getInput(); + + ActionResult result = processShipment.action(parameters, isStopped); + + assertEquals("Should return error type for invalid action", Result.Type.ERROR, result.getType()); + } + } + + /** + * Tests processing of multiple shipments through the {@code action} method, + * ensuring all shipments are processed individually and successfully. + * @throws Exception If processing fails unexpectedly. + */ + @Test + public void testActionWithMultipleShipments() throws Exception { + JSONObject parameters = new JSONObject(); + parameters.put("DocAction", "CO"); + MutableBoolean isStopped = new MutableBoolean(false); + + ShipmentInOut mockShipment2 = mock(ShipmentInOut.class); + ShipmentInOut mockShipment3 = mock(ShipmentInOut.class); + List multipleShipments = Arrays.asList(mockShipment, mockShipment2, mockShipment3); + + OBError successResult = new OBError(); + successResult.setType("Success"); + + try (MockedStatic requestContextMock = mockStatic(RequestContext.class); + MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { + + requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); + when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); + when(mockWeldUtils.getInstance(ProcessShipmentUtil.class)).thenReturn(mockProcessShipmentUtil); + + when(mockShipment.getId()).thenReturn("testId1"); + when(mockShipment2.getId()).thenReturn("testId2"); + when(mockShipment3.getId()).thenReturn("testId3"); + + when(mockProcessShipmentUtil.process( + anyString(), + anyString(), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + )).thenReturn(successResult); + + messageMock.when(() -> OBMessageUtils.messageBD(anyString())) + .thenReturn("Test message"); + + doReturn(multipleShipments).when(processShipment).getInputContents(any()); + doReturn(mockData).when(processShipment).getInput(); + + ActionResult result = processShipment.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + verify(mockProcessShipmentUtil, times(3)).process( + anyString(), + anyString(), + any(VariablesSecureApp.class), + any(DalConnectionProvider.class) + ); + } + } + + /** + * Verifies the correct input class type is returned by the {@code getInputClass} method. + */ + @Test + public void testGetInputClass() { + assertEquals("Should return ShipmentInOut.class", ShipmentInOut.class, processShipment.getInputClass()); + } + + +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java new file mode 100644 index 000000000..f7fdbc2d4 --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java @@ -0,0 +1,47 @@ +package com.smf.jobs.defaults.invoices; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.apache.commons.lang.mutable.MutableBoolean; +import org.codehaus.jettison.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.model.common.order.Order; + +import com.smf.jobs.ActionResult; +import com.smf.jobs.Result; + +@RunWith(MockitoJUnitRunner.class) +public class CreateFromOrderTest { + + @Spy + @InjectMocks + private CreateFromOrder createFromOrder; + + + @Before + public void setUp() { + } + + @Test + public void testActionWithRefreshButton() throws Exception { + JSONObject parameters = new JSONObject(); + parameters.put("_buttonValue", "REFRESH"); + MutableBoolean isStopped = new MutableBoolean(false); + + ActionResult result = createFromOrder.action(parameters, isStopped); + + assertNotNull("Result should not be null", result); + assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + } + + @Test + public void testGetInputClass() { + assertEquals("Should return Order.class", Order.class, createFromOrder.getInputClass()); + } +} diff --git a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java new file mode 100644 index 000000000..421b055bc --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java @@ -0,0 +1,102 @@ +package com.smf.jobs.defaults.invoices; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class CreateFromOrdersHQLTransformerTest { + + private CreateFromOrdersHQLTransformer transformer; + private String baseHqlQuery; + + @BeforeEach + void setUp() { + transformer = new CreateFromOrdersHQLTransformer(); + baseHqlQuery = "SELECT * FROM Orders WHERE includeTax = @linesIncludeTaxes@"; + } + + @Test + void testTransformHqlQueryWhenLinesIncludeTaxesIsTrue() { + Map requestParameters = new HashMap<>(); + requestParameters.put("linesIncludeTaxes", "true"); + Map queryNamedParameters = new HashMap<>(); + + String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); + + assertEquals("SELECT * FROM Orders WHERE includeTax = 'Y'", result); + } + + @Test + void testTransformHqlQueryWhenLinesIncludeTaxesIsFalse() { + Map requestParameters = new HashMap<>(); + requestParameters.put("linesIncludeTaxes", "false"); + Map queryNamedParameters = new HashMap<>(); + + String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); + + assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + } + + @Test + void testTransformHqlQueryWhenLinesIncludeTaxesParameterIsMissing() { + Map requestParameters = new HashMap<>(); + Map queryNamedParameters = new HashMap<>(); + + String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); + + assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + } + + @Test + void testTransformHqlQueryWithMultipleReplacements() { + String queryWithMultipleReplacements = + "SELECT * FROM Orders WHERE includeTax = @linesIncludeTaxes@ AND otherField = @linesIncludeTaxes@"; + Map requestParameters = new HashMap<>(); + requestParameters.put("linesIncludeTaxes", "true"); + Map queryNamedParameters = new HashMap<>(); + + String result = transformer.transformHqlQuery(queryWithMultipleReplacements, requestParameters, queryNamedParameters); + + assertEquals("SELECT * FROM Orders WHERE includeTax = 'Y' AND otherField = 'Y'", result); + } + + @Test + void testTransformHqlQueryWithInvalidBooleanValue() { + Map requestParameters = new HashMap<>(); + requestParameters.put("linesIncludeTaxes", "invalid_boolean"); + Map queryNamedParameters = new HashMap<>(); + + String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); + + assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + } + + @Test + void testTransformHqlQueryWithEmptyQuery() { + Map requestParameters = new HashMap<>(); + requestParameters.put("linesIncludeTaxes", "true"); + Map queryNamedParameters = new HashMap<>(); + + String result = transformer.transformHqlQuery("", requestParameters, queryNamedParameters); + + assertEquals("", result); + } + + @Test + void testTransformHqlQueryWithNullQuery() { + Map requestParameters = new HashMap<>(); + requestParameters.put("linesIncludeTaxes", "true"); + Map queryNamedParameters = new HashMap<>(); + + assertThrows(NullPointerException.class, () -> { + transformer.transformHqlQuery(null, requestParameters, queryNamedParameters); + }); + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java new file mode 100644 index 000000000..49bb36b37 --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java @@ -0,0 +1,142 @@ +package com.smf.jobs.defaults.offerPick; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.openbravo.base.provider.OBProvider; +import org.openbravo.dal.service.OBDal; +import org.openbravo.model.ad.system.Client; +import org.openbravo.model.common.enterprise.Organization; +import org.openbravo.model.pricing.priceadjustment.OrganizationFilter; +import org.openbravo.model.pricing.priceadjustment.PriceAdjustment; +import org.hibernate.Session; + +@ExtendWith(MockitoExtension.class) +public class OfferAddOrgTest { + + @Mock + private OBDal obDal; + + @Mock + private PriceAdjustment priceAdjustment; + + @Mock + private Client client; + + @Mock + private Organization organization; + + @Mock + private Session session; + + private OfferAddOrg offerAddOrg; + + @BeforeEach + public void setup() { + offerAddOrg = new OfferAddOrg(); + } + + @Test + public void testDoPickAndExecuteSingleOrganization() throws JSONException { + try (MockedStatic mockedOBDal = mockStatic(OBDal.class); + MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { + + // Arrange + mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); + when(obDal.getSession()).thenReturn(session); + when(priceAdjustment.getClient()).thenReturn(client); + + JSONArray selectedLines = new JSONArray(); + JSONObject orgJson = new JSONObject(); + orgJson.put("id", "testId"); + selectedLines.put(orgJson); + + when(obDal.getProxy(eq(Organization.ENTITY_NAME), eq("testId"))).thenReturn(organization); + + OBProvider obProvider = mock(OBProvider.class); + OrganizationFilter mockOrgFilter = mock(OrganizationFilter.class); + + mockedOBProvider.when(OBProvider::getInstance).thenReturn(obProvider); + when(obProvider.get(OrganizationFilter.class)).thenReturn(mockOrgFilter); + + // Act + offerAddOrg.doPickAndExecute(priceAdjustment, selectedLines); + + // Assert + verify(mockOrgFilter).setActive(true); + verify(mockOrgFilter).setClient(client); + verify(mockOrgFilter).setOrganization(organization); + verify(mockOrgFilter).setPriceAdjustment(priceAdjustment); + verify(obDal).save(mockOrgFilter); + } + } + + @Test + public void testDoPickAndExecuteMultipleOrganizations() throws JSONException { + try (MockedStatic mockedOBDal = mockStatic(OBDal.class); + MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { + + // Arrange + mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); + when(obDal.getSession()).thenReturn(session); + when(priceAdjustment.getClient()).thenReturn(client); + + JSONArray selectedLines = new JSONArray(); + for (int i = 0; i < 150; i++) { + JSONObject orgJson = new JSONObject(); + orgJson.put("id", "testId" + i); + selectedLines.put(orgJson); + } + + when(obDal.getProxy(eq(Organization.ENTITY_NAME), anyString())).thenReturn(organization); + + OBProvider obProvider = mock(OBProvider.class); + OrganizationFilter mockOrgFilter = mock(OrganizationFilter.class); + + mockedOBProvider.when(OBProvider::getInstance).thenReturn(obProvider); + when(obProvider.get(OrganizationFilter.class)).thenReturn(mockOrgFilter); + + // Act + offerAddOrg.doPickAndExecute(priceAdjustment, selectedLines); + + // Assert + verify(obDal, times(150)).save(any()); + verify(obDal, times(2)).flush(); + verify(session, times(2)).clear(); + } + } + + @Test + public void testDoPickAndExecuteInvalidJSON() throws JSONException { + try (MockedStatic mockedOBDal = mockStatic(OBDal.class)) { + // Arrange + mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); + + JSONArray selectedLines = new JSONArray(); + JSONObject invalidJson = new JSONObject(); + invalidJson.put("invalid", "value"); + selectedLines.put(invalidJson); + + + // Act & Assert + assertThrows(JSONException.class, () -> + offerAddOrg.doPickAndExecute(priceAdjustment, selectedLines)); + } + } + + @Test + public void testGetJSONName() { + assertEquals("Conforgprocess", offerAddOrg.getJSONName()); + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java new file mode 100644 index 000000000..cae158382 --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java @@ -0,0 +1,126 @@ +package com.smf.jobs.defaults.offerPick; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.openbravo.base.provider.OBProvider; +import org.openbravo.dal.service.OBDal; +import org.openbravo.model.ad.system.Client; +import org.openbravo.model.common.enterprise.Organization; +import org.openbravo.model.common.plm.ProductCategory; +import org.openbravo.model.pricing.priceadjustment.PriceAdjustment; +import org.hibernate.Session; + +@ExtendWith(MockitoExtension.class) +public class OfferAddProductCategoryTest { + + @Mock + private OBDal obDal; + + @Mock + private PriceAdjustment priceAdjustment; + + @Mock + private Client client; + + @Mock + private Organization organization; + + @Mock + private Session session; + + private OfferAddProductCategory offerAddProductCategory; + + @BeforeEach + public void setup() { + offerAddProductCategory = new OfferAddProductCategory(); + when(priceAdjustment.getClient()).thenReturn(client); + when(priceAdjustment.getOrganization()).thenReturn(organization); + } + + @Test + public void testDoPickAndExecuteSingleProductCategory() throws JSONException { + try (MockedStatic mockedOBDal = mockStatic(OBDal.class); + MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { + + // Arrange + mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); + when(obDal.getSession()).thenReturn(session); + + JSONArray selectedLines = new JSONArray(); + JSONObject productCatJson = new JSONObject(); + productCatJson.put("id", "testId"); + selectedLines.put(productCatJson); + + ProductCategory productCategory = mock(ProductCategory.class); + when(obDal.getProxy(eq(ProductCategory.ENTITY_NAME), eq("testId"))).thenReturn(productCategory); + + OBProvider obProvider = mock(OBProvider.class); + org.openbravo.model.pricing.priceadjustment.ProductCategory mockProductCategory = + mock(org.openbravo.model.pricing.priceadjustment.ProductCategory.class); + + mockedOBProvider.when(OBProvider::getInstance).thenReturn(obProvider); + when(obProvider.get(org.openbravo.model.pricing.priceadjustment.ProductCategory.class)) + .thenReturn(mockProductCategory); + + // Act + offerAddProductCategory.doPickAndExecute(priceAdjustment, selectedLines); + + // Assert + verify(mockProductCategory).setActive(true); + verify(mockProductCategory).setClient(client); + verify(mockProductCategory).setOrganization(organization); + verify(mockProductCategory).setPriceAdjustment(priceAdjustment); + verify(mockProductCategory).setProductCategory(productCategory); + verify(obDal).save(mockProductCategory); + } + } + + @Test + public void testDoPickAndExecuteMultipleProductCategories() throws JSONException { + try (MockedStatic mockedOBDal = mockStatic(OBDal.class); + MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { + + // Arrange + mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); + when(obDal.getSession()).thenReturn(session); + + JSONArray selectedLines = new JSONArray(); + for (int i = 0; i < 150; i++) { + JSONObject productCatJson = new JSONObject(); + productCatJson.put("id", "testId" + i); + selectedLines.put(productCatJson); + } + + ProductCategory productCategory = mock(ProductCategory.class); + when(obDal.getProxy(eq(ProductCategory.ENTITY_NAME), anyString())).thenReturn(productCategory); + + OBProvider obProvider = mock(OBProvider.class); + org.openbravo.model.pricing.priceadjustment.ProductCategory mockProductCategory = + mock(org.openbravo.model.pricing.priceadjustment.ProductCategory.class); + + mockedOBProvider.when(OBProvider::getInstance).thenReturn(obProvider); + when(obProvider.get(org.openbravo.model.pricing.priceadjustment.ProductCategory.class)) + .thenReturn(mockProductCategory); + + // Act + offerAddProductCategory.doPickAndExecute(priceAdjustment, selectedLines); + + // Assert + verify(obDal, times(150)).save(any()); + verify(obDal, times(2)).flush(); + verify(session, times(2)).clear(); + } + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java new file mode 100644 index 000000000..7e222f5ee --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java @@ -0,0 +1,183 @@ +package com.smf.jobs.defaults.offerPick; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.hibernate.Session; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnitRunner; +import org.openbravo.base.provider.OBProvider; +import org.openbravo.dal.service.OBDal; +import org.openbravo.model.ad.system.Client; +import org.openbravo.model.common.enterprise.Organization; +import org.openbravo.model.common.plm.Product; +import org.openbravo.model.pricing.priceadjustment.PriceAdjustment; + +/** + * Unit tests for the {@link OfferAddProduct} class. + * This test class validates the functionality of the OfferAddProduct class + * by testing its behavior in scenarios such as adding a product to an offer, + * processing multiple products, handling invalid JSON, and retrieving its JSON name. + * It uses Mockito for mocking dependencies and ensures the methods work as intended. + */ +@RunWith(MockitoJUnitRunner.class) +public class OfferAddProductTest { + + private OfferAddProduct offerAddProduct; + + @Mock + private OBDal obDal; + + @Mock + private Product product; + + @Mock + private PriceAdjustment priceAdjustment; + + @Mock + private Client client; + + @Mock + private Organization organization; + + @Mock + private org.openbravo.model.pricing.priceadjustment.Product priceAdjustmentProduct; + + @Mock + private Session session; + + /** + * Sets up the required mock objects and default behavior + * before executing each test. + */ + @Before + public void setUp() { + offerAddProduct = new OfferAddProduct(); + + when(priceAdjustment.getClient()).thenReturn(client); + when(priceAdjustment.getOrganization()).thenReturn(organization); + when(obDal.getSession()).thenReturn(session); + } + + /** + * Tests the doPickAndExecute method for the basic scenario where a single product + * is added to an offer. It validates that all operations are called as expected. + * + * @throws Exception if there is any issue during JSON processing or mock interaction + */ + @Test + public void testDoPickAndExecute() throws Exception { + JSONArray selectedLines = new JSONArray(); + JSONObject productJson = new JSONObject(); + productJson.put("id", "test-product-id"); + selectedLines.put(productJson); + + try (MockedStatic obDalStatic = mockStatic(OBDal.class); + MockedStatic obProviderStatic = mockStatic(OBProvider.class)) { + + obDalStatic.when(OBDal::getInstance).thenReturn(obDal); + when(obDal.getProxy(eq(Product.ENTITY_NAME), anyString())).thenReturn(product); + + OBProvider obProvider = mock(OBProvider.class); + obProviderStatic.when(OBProvider::getInstance).thenReturn(obProvider); + when(obProvider.get(org.openbravo.model.pricing.priceadjustment.Product.class)) + .thenReturn(priceAdjustmentProduct); + + doNothing().when(priceAdjustmentProduct).setActive(anyBoolean()); + doNothing().when(priceAdjustmentProduct).setClient(any(Client.class)); + doNothing().when(priceAdjustmentProduct).setOrganization(any(Organization.class)); + doNothing().when(priceAdjustmentProduct).setPriceAdjustment(any(PriceAdjustment.class)); + doNothing().when(priceAdjustmentProduct).setProduct(any(Product.class)); + doNothing().when(obDal).save(any()); + doNothing().when(obDal).flush(); + doNothing().when(session).clear(); + + offerAddProduct.doPickAndExecute(priceAdjustment, selectedLines); + + verify(priceAdjustmentProduct).setActive(true); + verify(priceAdjustmentProduct).setClient(client); + verify(priceAdjustmentProduct).setOrganization(organization); + verify(priceAdjustmentProduct).setPriceAdjustment(priceAdjustment); + verify(priceAdjustmentProduct).setProduct(product); + verify(obDal).save(priceAdjustmentProduct); + } + } + + /** + * Tests the getJSONName method to ensure it returns the correct JSON name. + */ + @Test + public void testGetJSONName() { + assert "Confprodprocess".equals(offerAddProduct.getJSONName()); + } + + /** + * Tests the doPickAndExecute method when processing multiple products. + * Ensures that the appropriate operations are executed multiple times. + * + * @throws Exception if there is any issue during JSON processing or mock interaction + */ + @Test + public void testDoPickAndExecuteWithMultipleProducts() throws Exception { + JSONArray selectedLines = new JSONArray(); + for (int i = 0; i < 150; i++) { + JSONObject productJson = new JSONObject(); + productJson.put("id", "test-product-id-" + i); + selectedLines.put(productJson); + } + + try (MockedStatic obDalStatic = mockStatic(OBDal.class); + MockedStatic obProviderStatic = mockStatic(OBProvider.class)) { + + obDalStatic.when(OBDal::getInstance).thenReturn(obDal); + when(obDal.getProxy(eq(Product.ENTITY_NAME), anyString())).thenReturn(product); + + OBProvider obProvider = mock(OBProvider.class); + obProviderStatic.when(OBProvider::getInstance).thenReturn(obProvider); + when(obProvider.get(org.openbravo.model.pricing.priceadjustment.Product.class)) + .thenReturn(priceAdjustmentProduct); + + doNothing().when(priceAdjustmentProduct).setActive(anyBoolean()); + doNothing().when(priceAdjustmentProduct).setClient(any(Client.class)); + doNothing().when(priceAdjustmentProduct).setOrganization(any(Organization.class)); + doNothing().when(priceAdjustmentProduct).setPriceAdjustment(any(PriceAdjustment.class)); + doNothing().when(priceAdjustmentProduct).setProduct(any(Product.class)); + doNothing().when(obDal).save(any()); + doNothing().when(obDal).flush(); + doNothing().when(session).clear(); + + offerAddProduct.doPickAndExecute(priceAdjustment, selectedLines); + + verify(obDal, times(150)).save(any()); + verify(obDal, atLeast(1)).flush(); + verify(session, atLeast(1)).clear(); + } + } + + /** + * Tests the doPickAndExecute method when the input JSON is invalid. + * Expects a {@link JSONException} to be thrown. + * + * @throws Exception if the test encounters any unexpected errors + */ + @Test(expected = JSONException.class) + public void testDoPickAndExecuteWithInvalidJSON() throws Exception { + JSONArray selectedLines = new JSONArray(); + JSONObject invalidJson = new JSONObject(); + selectedLines.put(invalidJson); + + try (MockedStatic obDalStatic = mockStatic(OBDal.class)) { + obDalStatic.when(OBDal::getInstance).thenReturn(obDal); + offerAddProduct.doPickAndExecute(priceAdjustment, selectedLines); + } + } +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java b/src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java new file mode 100644 index 000000000..65b67f454 --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java @@ -0,0 +1,121 @@ +package com.smf.jobs.defaults.provider; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockitoAnnotations; +import org.openbravo.client.kernel.ComponentProvider; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +import javax.enterprise.context.ApplicationScoped; + +/** + * Test suite for the JobsComponentProvider class, responsible for testing its functionality and annotations. + * This class verifies the following: + *
    + *
  • Presence and values of specific annotations.
  • + *
  • Constant definitions.
  • + *
  • Behavior of methods with and without expected exceptions.
  • + *
  • Proper structure and content of global component resources.
  • + *
+ */ +public class JobsComponentProviderTest { + + private JobsComponentProvider jobsComponentProvider; + + /** + * Sets up the testing environment by initializing mocks and the instance of the class under test. + */ + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + jobsComponentProvider = new JobsComponentProvider(); + } + + /** + * Tests the presence and value of the {@link ComponentProvider.Qualifier} annotation in the class under test. + */ + @Test + public void testComponentProviderQualifier() { + ComponentProvider.Qualifier qualifier = jobsComponentProvider.getClass().getAnnotation(ComponentProvider.Qualifier.class); + assertNotNull("ComponentProvider.Qualifier annotation should be present", qualifier); + assertEquals("Qualifier value should match COMPONENT_TYPE", + JobsComponentProvider.COMPONENT_TYPE, + qualifier.value()); + } + + /** + * Tests the value of the COMPONENT_TYPE constant. + */ + @Test + public void testConstantComponentType() { + assertEquals("COMPONENT_TYPE should be 'JOBSPR_CompProv'", + "JOBSPR_CompProv", + JobsComponentProvider.COMPONENT_TYPE); + } + + /** + * Verifies that calling getComponent with specific parameters throws an {@link IllegalArgumentException}. + * + * @throws IllegalArgumentException when an invalid component ID is passed. + */ + @Test(expected = IllegalArgumentException.class) + public void testGetComponentThrowsException() { + Map parameters = new HashMap<>(); + jobsComponentProvider.getComponent("testComponentId", parameters); + } + + /** + * Tests the contents and properties of the global component resources list. + * Ensures it is non-null, non-empty, contains specific elements, and has the expected size. + */ + @Test + public void testGetGlobalComponentResources() { + List globalResources = + jobsComponentProvider.getGlobalComponentResources(); + + assertNotNull("Global resources list should not be null", globalResources); + assertFalse("Global resources list should not be empty", globalResources.isEmpty()); + + assertEquals("Should have exactly 3 global resources", 3, globalResources.size()); + + boolean hasProcessRecordsJs = false; + boolean hasCloneRecordJs = false; + boolean hasCreateFromOrdersJs = false; + + for (Object resource : globalResources) { + String resourceString = resource.toString(); + if (resourceString.contains("processRecords.js")) { + hasProcessRecordsJs = true; + } + if (resourceString.contains("ob-clone-record.js")) { + hasCloneRecordJs = true; + } + if (resourceString.contains("createFromOrders.js")) { + hasCreateFromOrdersJs = true; + } + } + + assertTrue("Should contain processRecords.js", hasProcessRecordsJs); + assertTrue("Should contain ob-clone-record.js", hasCloneRecordJs); + assertTrue("Should contain createFromOrders.js", hasCreateFromOrdersJs); + } + + /** + * Verifies the presence of the {@link ApplicationScoped} annotation on the class under test. + */ + @Test + public void testApplicationScopedAnnotation() { + ApplicationScoped applicationScoped = + jobsComponentProvider.getClass().getAnnotation(ApplicationScoped.class); + assertNotNull("Class should be annotated with @ApplicationScoped", applicationScoped); + } +} \ No newline at end of file From cb2a0ff76ba51d1e98d449d1e5dc06df5fd3681c Mon Sep 17 00:00:00 2001 From: Emi-Polliotti Date: Tue, 17 Dec 2024 14:12:01 -0300 Subject: [PATCH 3/4] Feature ETP-870: Resolved SonarQube suggestions --- pipelines/unittests/Jenkinsfile | 43 +++- pipelines/unittests/JenkinsfileOracle | 38 +++ ...ReportValuationStockAddParametersTest.java | 24 +- .../ReportValuationStockBuildDataTest.java | 9 +- .../ReportValuationStockGetReportTest.java | 41 ++-- .../ReportValuationStockPrintTest.java | 36 +-- .../ReportValuationStockSummaryTest.java | 45 ++-- .../smf/jobs/defaults/CloneOrderHookTest.java | 58 +++-- .../src/com/smf/jobs/defaults/PostTest.java | 219 ------------------ .../jobs/defaults/ProcessInvoicesTest.java | 84 ++++--- .../defaults/ProcessOrdersDefaultsTest.java | 24 +- .../smf/jobs/defaults/ProcessOrdersTest.java | 66 +----- .../jobs/defaults/ProcessShipmentTest.java | 91 +++++--- .../invoices/CreateFromOrderTest.java | 31 ++- .../CreateFromOrdersHQLTransformerTest.java | 91 ++++++-- .../defaults/offerPick/OfferAddOrgTest.java | 87 +++++-- .../OfferAddProductCategoryTest.java | 50 +++- .../offerPick/OfferAddProductTest.java | 15 +- .../provider/JobsComponentProviderTest.java | 7 +- src-test/src/com/smf/test/CoreTestSuite.java | 69 ++++++ 20 files changed, 652 insertions(+), 476 deletions(-) delete mode 100644 src-test/src/com/smf/jobs/defaults/PostTest.java create mode 100644 src-test/src/com/smf/test/CoreTestSuite.java diff --git a/pipelines/unittests/Jenkinsfile b/pipelines/unittests/Jenkinsfile index 8abf08af1..b85a56d61 100644 --- a/pipelines/unittests/Jenkinsfile +++ b/pipelines/unittests/Jenkinsfile @@ -254,7 +254,7 @@ spec: try { echo "--------------- Running WebserviceTestSuite ---------------" sh "./gradlew test --tests org.openbravo.test.WebserviceTestSuite --info" - sh "mv build/jacoco/test.exec build/jacoco/test1.exec" + sh "mv build/jacoco/test.exec build/jacoco/test0.exec" echo "--------------- WebserviceTestSuite Successful ---------------" currentBuild.result = SUCCESS } catch (Exception e) { @@ -282,6 +282,47 @@ spec: } } // __________________________________________________________________________________________ +// ------------------------------ com.smf.* TESTS ------------------------------------------ + stage ('Core Test Suite') { // MARK: CoreTestSuite Test Suite + when { + expression { + env.STATUSBUILD == "1" + } + } + steps { + sh "./pipelines/unittests/build-update.sh ${REPO_NAME} ${COMMIT_INPROGRESS_STATUS} \"Running Test Suites\" ${ACCESS_TOKEN} ${GIT_COMMIT} ${BUILD_URL} \"${CONTEXT_BUILD}\"" + container('compiler') { + script { + dir(REPO_NAME) { + try { + echo "--------------- Running CoreTestSuite ---------------" + sh "./gradlew test --tests com.smf.test.CoreTestSuite --info" + sh "mv build/jacoco/test.exec build/jacoco/test1.exec" + echo "--------------- CoreTestSuite Successful ---------------" + currentBuild.result = SUCCESS + } catch (Exception e) { + echo "--------------- CoreTestSuite Failed ---------------" + echo 'Exception occurred: ' + e.toString() + currentBuild.result = UNSTABLE + unstable('CoreTestSuite Failed') + env.STATUSTEST = "0" + } finally { + publishHTML([ + allowMissing: false, + alwaysLinkToLastBuild: false, + keepAll: true, + reportDir: 'build/reports/tests/test', + reportFiles: '*.html', + reportName: 'com.smf.* TESTS REPORT', + reportTitles: '' + ]) + } + } + } + } + } + } +// __________________________________________________________________________________________ // ------------------------------- STANDALONE TEST ------------------------------------------ stage ('Standalone Test Suite') { // MARK: Standalone Test Suite when { diff --git a/pipelines/unittests/JenkinsfileOracle b/pipelines/unittests/JenkinsfileOracle index 93c0f1936..889ffa11e 100644 --- a/pipelines/unittests/JenkinsfileOracle +++ b/pipelines/unittests/JenkinsfileOracle @@ -248,6 +248,44 @@ spec: } } } +// __________________________________________________________________________________________ +// ------------------------------ com.smf.* TESTS ------------------------------------------ + stage ('Core Test Suite') { // MARK: com.smf.* Test Suite + when { + expression { + env.STATUSBUILD == "1" + } + } + steps { + container('compiler') { + script { + dir(REPO_NAME) { + try { + echo "--------------- Running CoreTestSuite ---------------" + sh "./gradlew test --tests com.smf.test.CoreTestSuite --info" + echo "--------------- CoreTestSuite Successful ---------------" + } catch (Exception e) { + echo "--------------- CoreTestSuite Failed ---------------" + echo 'Exception occurred: ' + e.toString() + currentBuild.result = UNSTABLE + unstable('CoreTestSuite Failed') + env.STATUSTEST = "0" + } finally { + publishHTML([ + allowMissing: true, + alwaysLinkToLastBuild: false, + keepAll: true, + reportDir: 'build/reports/tests/test', + reportFiles: '*.html', + reportName: 'com.smf.* TESTS REPORT', + reportTitles: '' + ]) + } + } + } + } + } + } //___________________________________________________________________________________________ // ------------------------------- STANDALONE TEST ------------------------------------------ stage ('Standalone Test Suite'){ diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java index b471cd39a..db393b0ae 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java @@ -35,9 +35,17 @@ import org.openbravo.dal.core.OBContext; import org.openbravo.erpCommon.utility.OBMessageUtils; +/** + * Unit test class for {@link ReportValuationStock#addAdditionalParameters}. + * It validates the correct behavior when additional parameters are added + * to the report generation process. + */ @RunWith(MockitoJUnitRunner.class) public class ReportValuationStockAddParametersTest { + /** + * Rule to handle expected exceptions during test execution. + */ @Rule public ExpectedException thrown = ExpectedException.none(); @@ -69,6 +77,11 @@ public class ReportValuationStockAddParametersTest { private static final String TEST_CURRENCY_ID = "testCurrencyId"; private static final String TEST_DATE = "2024-01-01"; + /** + * Set up the test environment, including mocks and static contexts. + * + * @throws ServletException if an error occurs during setup + */ @Before public void setUp() throws ServletException { reportValuationStock = spy(new ReportValuationStock()); @@ -102,6 +115,9 @@ public void setUp() throws ServletException { ); } + /** + * Clean up static mocks after each test case execution. + */ @After public void tearDown() { if (mockedRequestContext != null) { @@ -118,6 +134,12 @@ public void tearDown() { } } + /** + * Tests that additional parameters are added correctly to the report process + * when valid input JSON content is provided. + * + * @throws Exception if an unexpected error occurs during the test + */ @Test public void testAddAdditionalParametersValidInput() throws Exception { Map parameters = new HashMap<>(); @@ -141,6 +163,4 @@ public void testAddAdditionalParametersValidInput() throws Exception { assertNotNull("Parameters should not be null", parameters); assertEquals("PDF", parameters.get("OUTPUT_FORMAT")); } - - } \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java index f386c6cc4..7e19ef938 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java @@ -16,6 +16,7 @@ import javax.servlet.ServletException; +import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -70,6 +71,8 @@ public class ReportValuationStockBuildDataTest { private static final String TEST_CATEGORY_ID = "testCategoryId"; private static final String TEST_CURRENCY_ID = "testCurrencyId"; private static final String TEST_CLIENT_ID = "testClientId"; + private static final String WAREHOUSE_NOT_IN_LE = "WarehouseNotInLE"; + /** * Sets up the initial state required for the tests. Prepare mocks and retrieves @@ -127,9 +130,9 @@ public void testBuildDataWithNullLegalEntity() { when(mockOsp.getLegalEntity(any(Organization.class))).thenReturn(null); OBError mockError = mock(OBError.class); - when(mockError.getMessage()).thenReturn("WarehouseNotInLE"); + when(mockError.getMessage()).thenReturn(WAREHOUSE_NOT_IN_LE); obMessageUtilsMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn("WarehouseNotInLE"); + .thenReturn(WAREHOUSE_NOT_IN_LE); obMessageUtilsMock.when(() -> OBMessageUtils.translateError(anyString())) .thenReturn(mockError); @@ -148,7 +151,7 @@ public void testBuildDataWithNullLegalEntity() { } catch (Exception e) { assertTrue("Expected ServletException", e.getCause() instanceof ServletException); assertTrue("Expected correct error message", - e.getCause().getMessage().contains("WarehouseNotInLE")); + StringUtils.contains(e.getCause().getMessage(), WAREHOUSE_NOT_IN_LE)); } } } diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java index 9945de1b0..d3cce1db6 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java @@ -36,6 +36,8 @@ @RunWith(MockitoJUnitRunner.class) public class ReportValuationStockGetReportTest { + private static final String PROCESS_TIME = "processTime"; + @Mock private VariablesSecureApp vars; @@ -62,6 +64,15 @@ public class ReportValuationStockGetReportTest { private static final String TEST_CLIENT = "TEST_CLIENT"; private static final String TEST_LANGUAGE = "en_US"; + private static final String DATE_NEXT = "dateNext"; + private static final String MAX_AGG_DATE = "maxAggDate"; + private static final String DATE_FORMAT = "dateFormat"; + private static final String ORG_IDS = "orgIds"; + private static final String ERROR_RESULT_NULL = "Result should not be null"; + private static final String ERROR_DATA_LENGTH = "Should return expected data length"; + private static final String ERROR_EXPECTED_DATA = "Should return expected data"; + + /** * Sets up the test environment by initializing the required objects * and configuring mock behaviors. @@ -104,14 +115,14 @@ public void testGetReportDataWithCostTypeAndNoWarehouseConsolidation() throws Ex ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( reportValuationStock, - vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, "processTime", + vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, PROCESS_TIME, "N", "STA", TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, - "orgIds", TEST_ORG, TEST_CLIENT, "dateNext", "maxAggDate", "dateFormat" + ORG_IDS, TEST_ORG, TEST_CLIENT, DATE_NEXT, MAX_AGG_DATE, DATE_FORMAT ); - assertNotNull("Result should not be null", result); - assertEquals("Should return expected data length", expectedData.length, result.length); - assertEquals("Should return expected data", expectedData[0], result[0]); + assertNotNull(ERROR_RESULT_NULL, result); + assertEquals(ERROR_DATA_LENGTH, expectedData.length, result.length); + assertEquals(ERROR_EXPECTED_DATA, expectedData[0], result[0]); } } @@ -134,14 +145,14 @@ public void testGetReportDataWithoutCostTypeAndWithWarehouseConsolidation() thro ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( reportValuationStock, - vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, true, "processTime", + vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, true, PROCESS_TIME, "N", null, TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, - "orgIds", TEST_ORG, TEST_CLIENT, "dateNext", "maxAggDate", "dateFormat" + ORG_IDS, TEST_ORG, TEST_CLIENT, DATE_NEXT, MAX_AGG_DATE, DATE_FORMAT ); - assertNotNull("Result should not be null", result); - assertEquals("Should return expected data length", expectedData.length, result.length); - assertEquals("Should return expected data", expectedData[0], result[0]); + assertNotNull(ERROR_RESULT_NULL, result); + assertEquals(ERROR_DATA_LENGTH, expectedData.length, result.length); + assertEquals(ERROR_EXPECTED_DATA, expectedData[0], result[0]); } } @@ -164,14 +175,14 @@ public void testGetReportDataWithoutCostTypeAndNoWarehouseConsolidation() throws ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( reportValuationStock, - vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, "processTime", + vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, PROCESS_TIME, "N", null, TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, - "orgIds", TEST_ORG, TEST_CLIENT, "dateNext", "maxAggDate", "dateFormat" + ORG_IDS, TEST_ORG, TEST_CLIENT, DATE_NEXT, MAX_AGG_DATE, DATE_FORMAT ); - assertNotNull("Result should not be null", result); - assertEquals("Should return expected data length", expectedData.length, result.length); - assertEquals("Should return expected data", expectedData[0], result[0]); + assertNotNull(ERROR_RESULT_NULL, result); + assertEquals(ERROR_DATA_LENGTH, expectedData.length, result.length); + assertEquals(ERROR_EXPECTED_DATA, expectedData[0], result[0]); } } diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java index 4309d1908..abf17c1dc 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java @@ -50,6 +50,12 @@ public class ReportValuationStockPrintTest { private static final String TEST_ALGORITHM_NAME = "Average Algorithm"; private static final String TEST_TRANSLATED_HEADER = "Translated Cost Header"; private static final String TEST_TRANSLATED_VALUATION = "Translated Valuation Header"; + private static final String NUMBER_FORMAT = "#,##0.00"; + private static final String ERROR_PARAMETERS_NULL = "Parameters should not be null"; + private static final String NUMBER_FORMAT_KEY = "NUMBERFORMAT"; + private static final String ERROR_DECIMAL_FORMAT = "Should have correct decimal format"; + private static final String COST_FORMAT_KEY = "COSTFORMAT"; + /** * Sets up the test environment by initializing mocks and reflective access to the method under test. @@ -72,7 +78,7 @@ public void setUp() throws Exception { when(vars.getSessionValue("#AD_ReportDecimalSeparator")).thenReturn("."); when(vars.getSessionValue("#AD_ReportGroupingSeparator")).thenReturn(","); - when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn("#,##0.00"); + when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn(NUMBER_FORMAT); when(vars.getJavaDateFormat()).thenReturn("yyyy-MM-dd"); when(costingAlgorithm.getName()).thenReturn(TEST_ALGORITHM_NAME); @@ -92,7 +98,7 @@ public void setUp() throws Exception { public void testPrintReportWithCostingAlgorithm() throws Exception { ReportValuationStockData[] testData = new ReportValuationStockData[0]; Map parameters = new HashMap<>(); - DecimalFormat mockFormat = new DecimalFormat("#,##0.00"); + DecimalFormat mockFormat = new DecimalFormat(NUMBER_FORMAT); try (MockedStatic obMessageUtilsMock = mockStatic(OBMessageUtils.class); MockedStatic utilityMock = mockStatic(Utility.class)) { @@ -117,7 +123,7 @@ public void testPrintReportWithCostingAlgorithm() throws Exception { parameters ); - assertNotNull("Parameters should not be null", parameters); + assertNotNull(ERROR_PARAMETERS_NULL, parameters); assertEquals("Should have correct cost header", TEST_TRANSLATED_HEADER, parameters.get("ALG_COST")); assertEquals("Should have correct valuation header", @@ -127,9 +133,9 @@ public void testPrintReportWithCostingAlgorithm() throws Exception { assertEquals("Should have correct date", TEST_DATE, parameters.get("DATE")); assertNotNull("Should have number format", - parameters.get("NUMBERFORMAT")); - assertEquals("Should have correct decimal format", - mockFormat, parameters.get("COSTFORMAT")); + parameters.get(NUMBER_FORMAT_KEY)); + assertEquals(ERROR_DECIMAL_FORMAT, + mockFormat, parameters.get(COST_FORMAT_KEY)); } } @@ -147,7 +153,7 @@ public void testPrintReportWithCostingAlgorithm() throws Exception { public void testPrintReportWithoutCostingAlgorithm() throws Exception { ReportValuationStockData[] testData = new ReportValuationStockData[0]; Map parameters = new HashMap<>(); - DecimalFormat mockFormat = new DecimalFormat("#,##0.00"); + DecimalFormat mockFormat = new DecimalFormat(NUMBER_FORMAT); try (MockedStatic utilityMock = mockStatic(Utility.class)) { utilityMock.when(() -> Utility.getFormat(any(), anyString())).thenReturn(mockFormat); @@ -162,7 +168,7 @@ public void testPrintReportWithoutCostingAlgorithm() throws Exception { parameters ); - assertNotNull("Parameters should not be null", parameters); + assertNotNull(ERROR_PARAMETERS_NULL, parameters); assertEquals("Should have empty cost header", "", parameters.get("ALG_COST")); assertEquals("Should have empty valuation header", @@ -172,9 +178,9 @@ public void testPrintReportWithoutCostingAlgorithm() throws Exception { assertEquals("Should have correct date", TEST_DATE, parameters.get("DATE")); assertNotNull("Should have number format", - parameters.get("NUMBERFORMAT")); - assertEquals("Should have correct decimal format", - mockFormat, parameters.get("COSTFORMAT")); + parameters.get(NUMBER_FORMAT_KEY)); + assertEquals(ERROR_DECIMAL_FORMAT, + mockFormat, parameters.get(COST_FORMAT_KEY)); } } @@ -211,11 +217,11 @@ public void testPrintReportWithCustomFormats() throws Exception { parameters ); - assertNotNull("Parameters should not be null", parameters); + assertNotNull(ERROR_PARAMETERS_NULL, parameters); assertNotNull("Should have number format with custom separators", - parameters.get("NUMBERFORMAT")); - assertEquals("Should have correct decimal format", - mockFormat, parameters.get("COSTFORMAT")); + parameters.get(NUMBER_FORMAT_KEY)); + assertEquals(ERROR_DECIMAL_FORMAT, + mockFormat, parameters.get(COST_FORMAT_KEY)); } } } \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java index 98a35f93a..ac827718d 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java @@ -29,12 +29,19 @@ public class ReportValuationStockSummaryTest { private Method getSummaryProductCategoriesMethod; + private static final String ERROR_RESULT_NULL = "Result should not be null"; + private static final String CATEGORY_NAME = "categoryName"; + private static final String TEST_CATEGORY = "TestCategory"; + private static final String TOTAL_COST = "totalCost"; + private static final String TEST_COST_VALUE = "100.00"; + private static final String ERROR_ONE_CATEGORY = "Should contain one category"; + + /** * Sets up the test environment by initializing reflective access to the method under test. * * @throws Exception if the method cannot be accessed. */ - @Before public void setUp() throws Exception { getSummaryProductCategoriesMethod = ReportValuationStock.class.getDeclaredMethod( @@ -76,7 +83,7 @@ public void testGetSummaryProductCategoriesWithEmptyData() throws Exception { (Object) data ); - assertNotNull("Result should not be null", result); + assertNotNull(ERROR_RESULT_NULL, result); assertEquals("Empty data should return empty result", 0, result.length); } @@ -92,8 +99,8 @@ public void testGetSummaryProductCategoriesWithEmptyData() throws Exception { @Test public void testGetSummaryProductCategoriesWithSingleCategory() throws Exception { ReportValuationStockData singleData = new ReportValuationStockData(); - setFieldValue(singleData, "categoryName", "TestCategory"); - setFieldValue(singleData, "totalCost", "100.00"); + setFieldValue(singleData, CATEGORY_NAME, TEST_CATEGORY); + setFieldValue(singleData, TOTAL_COST, TEST_COST_VALUE); ReportValuationStockData[] data = new ReportValuationStockData[] { singleData }; @@ -102,11 +109,11 @@ public void testGetSummaryProductCategoriesWithSingleCategory() throws Exception (Object) data ); - assertNotNull("Result should not be null", result); - assertEquals("Should contain one category", 1, result.length); - assertEquals("Should have correct category name", "TestCategory", + assertNotNull(ERROR_RESULT_NULL, result); + assertEquals(ERROR_ONE_CATEGORY, 1, result.length); + assertEquals("Should have correct category name", TEST_CATEGORY, result[0].getField("category")); - assertEquals("Should have correct cost", "100.00", + assertEquals("Should have correct cost", TEST_COST_VALUE, result[0].getField("cost")); } @@ -122,12 +129,12 @@ public void testGetSummaryProductCategoriesWithSingleCategory() throws Exception @Test public void testGetSummaryProductCategoriesWithMultipleEntriesSameCategory() throws Exception { ReportValuationStockData data1 = new ReportValuationStockData(); - setFieldValue(data1, "categoryName", "TestCategory"); - setFieldValue(data1, "totalCost", "100.00"); + setFieldValue(data1, CATEGORY_NAME, TEST_CATEGORY); + setFieldValue(data1, TOTAL_COST, TEST_COST_VALUE); ReportValuationStockData data2 = new ReportValuationStockData(); - setFieldValue(data2, "categoryName", "TestCategory"); - setFieldValue(data2, "totalCost", "50.00"); + setFieldValue(data2, CATEGORY_NAME, TEST_CATEGORY); + setFieldValue(data2, TOTAL_COST, "50.00"); ReportValuationStockData[] data = new ReportValuationStockData[] { data1, data2 }; @@ -136,9 +143,9 @@ public void testGetSummaryProductCategoriesWithMultipleEntriesSameCategory() thr (Object) data ); - assertNotNull("Result should not be null", result); - assertEquals("Should contain one category", 1, result.length); - assertEquals("Category name should match", "TestCategory", + assertNotNull(ERROR_RESULT_NULL, result); + assertEquals(ERROR_ONE_CATEGORY, 1, result.length); + assertEquals("Category name should match", TEST_CATEGORY, result[0].getField("category")); assertEquals("Total cost should be summed correctly", "150.00", result[0].getField("cost")); @@ -156,8 +163,8 @@ public void testGetSummaryProductCategoriesWithMultipleEntriesSameCategory() thr @Test public void testGetSummaryProductCategoriesWithNullCosts() throws Exception { ReportValuationStockData nullCostData = new ReportValuationStockData(); - setFieldValue(nullCostData, "categoryName", "TestCategory"); - setFieldValue(nullCostData, "totalCost", null); + setFieldValue(nullCostData, CATEGORY_NAME, TEST_CATEGORY); + setFieldValue(nullCostData, TOTAL_COST, null); ReportValuationStockData[] data = new ReportValuationStockData[] { nullCostData }; @@ -166,8 +173,8 @@ public void testGetSummaryProductCategoriesWithNullCosts() throws Exception { (Object) data ); - assertNotNull("Result should not be null", result); - assertEquals("Should contain one category", 1, result.length); + assertNotNull(ERROR_RESULT_NULL, result); + assertEquals(ERROR_ONE_CATEGORY, 1, result.length); assertEquals("Cost should be zero for null values", "0", result[0].getField("cost")); } diff --git a/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java b/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java index de57d080b..9942ac8b0 100644 --- a/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java +++ b/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java @@ -45,6 +45,13 @@ import org.openbravo.model.pricing.pricelist.PriceListVersion; import org.openbravo.service.db.CallStoredProcedure; +/** + * Test class for {@link CloneOrderHook}. + *

+ * This class performs unit tests for the {@link CloneOrderHook} class methods, + * ensuring the functionality of order cloning processes. + *

+ */ @RunWith(MockitoJUnitRunner.class) public class CloneOrderHookTest { @@ -88,6 +95,11 @@ public class CloneOrderHookTest { private MockedStatic mockedCallStoredProcedure; private Method cloneOrderMethod; + /** + * Sets up the test environment by initializing mocks and reflection method. + * + * @throws Exception if the reflection setup fails. + */ @Before public void setUp() throws Exception { cloneOrderMethod = CloneOrderHook.class.getDeclaredMethod( @@ -109,59 +121,53 @@ public void setUp() throws Exception { when(obDal.getSession()).thenReturn(session); } + /** + * Tests the {@code cloneOrder} method to verify proper order cloning. + * + * @throws Exception if the reflection invocation fails. + */ @Test public void testCloneOrder() throws Exception { - // Setup organization - Organization organization = mock(Organization.class); + mock(Organization.class); - // Setup order lines List originalOrderLines = new ArrayList<>(); originalOrderLines.add(originalOrderLine); when(originalOrder.getOrderLineList()).thenReturn(originalOrderLines); when(clonedOrder.getOrderLineList()).thenReturn(new ArrayList<>()); - // Setup basic order configuration when(originalOrder.getPriceList()).thenReturn(priceList); when(originalOrder.getClient()).thenReturn(client); when(originalOrder.isSalesTransaction()).thenReturn(true); when(priceList.getId()).thenReturn("testPriceListId"); when(client.getId()).thenReturn("testClientId"); - // Setup order line details when(originalOrderLine.getProduct()).thenReturn(product); when(product.getId()).thenReturn("testProductId"); when(originalOrderLine.getId()).thenReturn("testOrderLineId"); when(originalOrderLine.getOrderlineServiceRelationList()).thenReturn(new ArrayList<>()); - // Mock DalUtil copy OrderLine clonedOrderLine = mock(OrderLine.class); mockedDalUtil.when(() -> DalUtil.copy(any(OrderLine.class), eq(false))) .thenReturn(clonedOrderLine); - // Mock price list version query OBQuery mockQuery = mock(OBQuery.class); when(obDal.createQuery(eq(PriceListVersion.class), anyString())).thenReturn(mockQuery); when(mockQuery.setNamedParameter(anyString(), any())).thenReturn(mockQuery); when(mockQuery.list()).thenReturn(new ArrayList<>()); - // Mock stored procedure call CallStoredProcedure mockStoredProcedure = mock(CallStoredProcedure.class); when(mockStoredProcedure.call(anyString(), any(), any())).thenReturn(BigDecimal.ONE); mockedCallStoredProcedure.when(CallStoredProcedure::getInstance).thenReturn(mockStoredProcedure); - // Mock CloneOrderHookCaller CloneOrderHookCaller mockCaller = mock(CloneOrderHookCaller.class); mockedWeldUtils.when(() -> WeldUtils.getInstanceFromStaticBeanManager(CloneOrderHookCaller.class)) .thenReturn(mockCaller); doNothing().when(mockCaller).executeHook(any(Order.class)); - // Execute test Order result = (Order) cloneOrderMethod.invoke(cloneOrderHook, currentUser, originalOrder, clonedOrder); - // Verify results assertNotNull("Cloned order should not be null", result); - // Verify the basic order properties verify(clonedOrder).setDocumentAction("CO"); verify(clonedOrder).setDocumentStatus("DR"); verify(clonedOrder).setPosted("N"); @@ -174,18 +180,22 @@ public void testCloneOrder() throws Exception { verify(clonedOrder).setGrandTotalAmount(BigDecimal.ZERO); verify(clonedOrder).setSummedLineAmount(BigDecimal.ZERO); - // Verify DAL operations verify(obDal).save(clonedOrder); verify(obDal).flush(); verify(obDal).refresh(clonedOrder); - // Verify order line operations verify(clonedOrderLine).setSalesOrder(clonedOrder); verify(clonedOrderLine).setReservedQuantity(BigDecimal.ZERO); verify(clonedOrderLine).setDeliveredQuantity(BigDecimal.ZERO); verify(clonedOrderLine).setInvoicedQuantity(BigDecimal.ZERO); } + /** + * Tests the {@code getLineNetAmt} method to ensure it retrieves the correct line amount. + *

+ * It verifies that the query is executed correctly and returns the expected result. + *

+ */ @Test public void testGetLineNetAmt() { String testOrderId = "test-order-id"; @@ -205,39 +215,49 @@ public void testGetLineNetAmt() { verify(mockQuery).setParameter("orderId", testOrderId); } + /** + * Tests the {@code shouldCopyChildren} method. + *

+ * Ensures that the method always returns {@code false}. + *

+ */ @Test public void testShouldCopyChildren() { boolean result = cloneOrderHook.shouldCopyChildren(true); assertEquals("Should always return false regardless of input", false, result); } + /** + * Tests the {@code preCopy} method. + *

+ * Verifies that the original record is returned without modification. + *

+ */ @Test public void testPreCopy() { BaseOBObject result = cloneOrderHook.preCopy(originalOrder); assertEquals("Should return original record without modification", originalOrder, result); } + /** + * Cleans up the test environment and closes static mocks. + */ @After public void tearDown() { if (mockedOBDal != null) { mockedOBDal.close(); - System.out.println("mockedOBDal cerrado correctamente."); } if (mockedOBContext != null) { mockedOBContext.close(); - System.out.println("mockedOBContext cerrado correctamente."); } if (mockedWeldUtils != null) { mockedWeldUtils.close(); - System.out.println("mockedWeldUtils cerrado correctamente."); } if (mockedDalUtil != null) { mockedDalUtil.close(); - System.out.println("mockedDalUtil cerrado correctamente."); } if (mockedCallStoredProcedure != null) { mockedCallStoredProcedure.close(); - System.out.println("mockedCallStoredProcedure cerrado correctamente."); } } diff --git a/src-test/src/com/smf/jobs/defaults/PostTest.java b/src-test/src/com/smf/jobs/defaults/PostTest.java deleted file mode 100644 index 16ae525d1..000000000 --- a/src-test/src/com/smf/jobs/defaults/PostTest.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.smf.jobs.defaults; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.apache.commons.lang.mutable.MutableBoolean; -import org.codehaus.jettison.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.openbravo.base.model.Entity; -import org.openbravo.base.secureApp.VariablesSecureApp; -import org.openbravo.base.structure.BaseOBObject; -import org.openbravo.client.kernel.RequestContext; -import org.openbravo.dal.service.OBDal; -import org.openbravo.erpCommon.ad_actionButton.ActionButtonUtility; -import org.openbravo.erpCommon.utility.OBError; -import org.openbravo.erpCommon.utility.OBMessageUtils; -import org.openbravo.model.ad.system.Client; -import org.openbravo.model.common.enterprise.Organization; -import org.openbravo.service.db.DalConnectionProvider; - -import com.smf.jobs.ActionResult; -import com.smf.jobs.Result; - -@RunWith(MockitoJUnitRunner.class) -public class PostTest { - - @Spy - private Post post; - - @Mock - private OBDal obDal; - - @Mock - private RequestContext requestContext; - @Mock - private VariablesSecureApp vars; - @Mock - private BaseOBObject mockRecord; - @Mock - private Organization organization; - @Mock - private Client client; - @Mock - private Entity entity; - - @Before - public void setUp() { - - when(organization.getId()).thenReturn("testOrgId"); - when(entity.getTableId()).thenReturn("318"); - - when(mockRecord.getId()).thenReturn("testId"); - when(mockRecord.getEntity()).thenReturn(entity); - when(mockRecord.get("organization")).thenReturn(organization); - when(mockRecord.get("client")).thenReturn(client); - - } - - @Test - public void testActionWithMultipleSuccessfulPostings() throws Exception { - JSONObject parameters = new JSONObject(); - MutableBoolean isStopped = new MutableBoolean(false); - - BaseOBObject mockRecord2 = mock(BaseOBObject.class); - when(mockRecord2.getId()).thenReturn("testId2"); - when(mockRecord2.get("posted")).thenReturn("N"); - when(mockRecord2.getEntity()).thenReturn(entity); - when(mockRecord2.get("organization")).thenReturn(organization); - when(mockRecord2.get("client")).thenReturn(client); - - List records = Arrays.asList(mockRecord, mockRecord2); - - OBError successResult = new OBError(); - successResult.setType("Success"); - successResult.setMessage("Posted successfully"); - - try (MockedStatic requestContextMock = mockStatic(RequestContext.class); - MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class); - MockedStatic obDalMock = mockStatic(OBDal.class); - MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { - - requestContextMock.when(RequestContext::get).thenReturn(requestContext); - when(requestContext.getVariablesSecureApp()).thenReturn(vars); - obDalMock.when(OBDal::getInstance).thenReturn(obDal); - - actionButtonUtilityMock.when(() -> ActionButtonUtility.processButton( - any(VariablesSecureApp.class), - anyString(), - anyString(), - anyString(), - any(DalConnectionProvider.class) - )).thenReturn(successResult); - - messageMock.when(() -> OBMessageUtils.messageBD(anyString())).thenReturn("DJOBS_PostUnpostMessage"); - doReturn(records).when(post).getInputContents(any()); - - ActionResult result = post.action(parameters, isStopped); - - assertNotNull("Result should not be null", result); - assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); - verify(mockRecord, times(1)).getId(); - verify(mockRecord2, times(1)).getId(); - } - } - - @Test - public void testActionWithMixedResults() throws Exception { - JSONObject parameters = new JSONObject(); - MutableBoolean isStopped = new MutableBoolean(false); - - BaseOBObject mockRecord2 = mock(BaseOBObject.class); - when(mockRecord2.getId()).thenReturn("testId2"); - when(mockRecord2.get("posted")).thenReturn("N"); - when(mockRecord2.getEntity()).thenReturn(entity); - when(mockRecord2.get("organization")).thenReturn(organization); - when(mockRecord2.get("client")).thenReturn(client); - - List records = Arrays.asList(mockRecord, mockRecord2); - - OBError successResult = new OBError(); - successResult.setType("Success"); - OBError errorResult = new OBError(); - errorResult.setType("Error"); - - try (MockedStatic requestContextMock = mockStatic(RequestContext.class); - MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class); - MockedStatic obDalMock = mockStatic(OBDal.class); - MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { - - requestContextMock.when(RequestContext::get).thenReturn(requestContext); - when(requestContext.getVariablesSecureApp()).thenReturn(vars); - obDalMock.when(OBDal::getInstance).thenReturn(obDal); - - actionButtonUtilityMock.when(() -> ActionButtonUtility.processButton( - any(VariablesSecureApp.class), - eq("testId"), - anyString(), - anyString(), - any(DalConnectionProvider.class) - )).thenReturn(successResult); - - actionButtonUtilityMock.when(() -> ActionButtonUtility.processButton( - any(VariablesSecureApp.class), - eq("testId2"), - anyString(), - anyString(), - any(DalConnectionProvider.class) - )).thenReturn(errorResult); - - messageMock.when(() -> OBMessageUtils.messageBD(anyString())).thenReturn("DJOBS_PostUnpostMessage"); - doReturn(records).when(post).getInputContents(any()); - - ActionResult result = post.action(parameters, isStopped); - - assertNotNull("Result should not be null", result); - assertEquals("Should return warning type for mixed results", Result.Type.WARNING, result.getType()); - } - } - - @Test - public void testActionWithEmptyRecordList() throws Exception { - JSONObject parameters = new JSONObject(); - MutableBoolean isStopped = new MutableBoolean(false); - List records = Collections.emptyList(); - - try (MockedStatic requestContextMock = mockStatic(RequestContext.class); - MockedStatic obDalMock = mockStatic(OBDal.class)) { - - requestContextMock.when(RequestContext::get).thenReturn(requestContext); - when(requestContext.getVariablesSecureApp()).thenReturn(vars); - obDalMock.when(OBDal::getInstance).thenReturn(obDal); - - doReturn(records).when(post).getInputContents(any()); - - ActionResult result = post.action(parameters, isStopped); - - assertNotNull("Result should not be null", result); - assertEquals("Should return success type for empty list", Result.Type.SUCCESS, result.getType()); - } - } - - - @Test - public void testActionWithException() throws Exception { - JSONObject parameters = new JSONObject(); - MutableBoolean isStopped = new MutableBoolean(false); - List records = Collections.singletonList(mockRecord); - - try (MockedStatic requestContextMock = mockStatic(RequestContext.class); - MockedStatic obDalMock = mockStatic(OBDal.class)) { - - requestContextMock.when(RequestContext::get).thenReturn(requestContext); - when(requestContext.getVariablesSecureApp()).thenReturn(vars); - obDalMock.when(OBDal::getInstance).thenReturn(obDal); - - doReturn(records).when(post).getInputContents(any()); - doThrow(new RuntimeException("Test exception")).when(mockRecord).get("posted"); - - ActionResult result = post.action(parameters, isStopped); - - assertNotNull("Result should not be null", result); - assertEquals("Should return error type", Result.Type.ERROR, result.getType()); - assertEquals("Should return exception message", "Test exception", result.getMessage()); - } - } -} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java b/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java index 01cb3a7bf..a1da78a86 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java @@ -38,6 +38,7 @@ import org.openbravo.service.db.DalConnectionProvider; import org.openbravo.service.json.JsonUtils; +import com.smf.jobs.Action; import com.smf.jobs.ActionResult; import com.smf.jobs.Result; import com.smf.jobs.Data; @@ -47,12 +48,15 @@ * This class contains tests to validate the behavior of processing invoices * in various scenarios, such as handling void dates, verifying successful * processing, and ensuring proper pre-run setup. - * * It uses JUnit and Mockito for testing and mocking dependencies. */ @RunWith(MockitoJUnitRunner.class) public class ProcessInvoicesTest { + public static final String SUCCESS = "Success"; + public static final String SHOULD_RETURN_SUCCESS_TYPE = "Should return success type"; + + @Spy @InjectMocks private TestableProcessInvoices processInvoices; @@ -79,6 +83,8 @@ public class ProcessInvoicesTest { private Data mockData; private Method processInvoiceMethod; + private Method getInputContentsMethod; + /** * Sets up the test environment, including retrieving the private method @@ -96,6 +102,13 @@ public void setUp() throws Exception { String.class ); processInvoiceMethod.setAccessible(true); + + // Add reflection setup for getInputContents + getInputContentsMethod = Action.class.getDeclaredMethod( + "getInputContents", + Class.class + ); + getInputContentsMethod.setAccessible(true); } /** @@ -110,7 +123,7 @@ public void testProcessInvoiceWithoutVoidDates() throws Exception { String invoiceId = "test-invoice-id"; String docAction = "CO"; OBError expectedResult = new OBError(); - expectedResult.setType("Success"); + expectedResult.setType(SUCCESS); expectedResult.setMessage("Invoice processed successfully"); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { @@ -135,7 +148,7 @@ public void testProcessInvoiceWithoutVoidDates() throws Exception { null ); - assertEquals("Should return success type", "Success", result.getType()); + assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); assertEquals("Should return correct message", "Invoice processed successfully", result.getMessage()); } } @@ -155,7 +168,7 @@ public void testProcessInvoiceWithVoidDates() throws Exception { String voidAcctDate = "2024-01-15"; OBError expectedResult = new OBError(); - expectedResult.setType("Success"); + expectedResult.setType(SUCCESS); SimpleDateFormat jsonDateFormat = JsonUtils.createDateFormat(); Date testDate = jsonDateFormat.parse(voidDate); @@ -183,11 +196,31 @@ public void testProcessInvoiceWithVoidDates() throws Exception { voidAcctDate ); - assertEquals("Should return success type", "Success", result.getType()); + assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); } } /** + * A testable subclass of ProcessInvoices that exposes certain protected + * or private methods for testing purposes. + */ + public static class TestableProcessInvoices extends ProcessInvoices { + @Override + public Data getInput() { + return super.getInput(); + } + } + + /** + * Verifies that the getInputClass method returns the correct input class + * for processing invoices. + */ + @Test + public void testGetInputClass() { + assertEquals("Should return Invoice.class", Invoice.class, processInvoices.getInputClass()); + } + + /** * Tests the action method to ensure it correctly handles processing invoices * when the processing result is successful. * @@ -201,14 +234,17 @@ public void testActionWithSuccessfulProcessing() throws Exception { List mockInvoices = List.of(mockInvoice); OBError successResult = new OBError(); - successResult.setType("Success"); + successResult.setType(SUCCESS); - doReturn(mockInvoices).when(processInvoices).getInputContents(any()); + // Instead of using doReturn().when(), use reflection + when(getInputContentsMethod.invoke(processInvoices, Invoice.class)) + .thenReturn(mockInvoices); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); - when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)).thenReturn(mockProcessInvoiceUtil); + when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)) + .thenReturn(mockProcessInvoiceUtil); when(mockInvoice.getId()).thenReturn("testId"); when(mockProcessInvoiceUtil.process( anyString(), @@ -221,7 +257,7 @@ public void testActionWithSuccessfulProcessing() throws Exception { ActionResult result = processInvoices.action(parameters, isStopped); - assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + assertEquals(SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); } } @@ -240,7 +276,7 @@ public void testPreRunWithLockedInvoice() throws Exception { List mockInvoices = List.of(mockInvoice); OBError successResult = new OBError(); - successResult.setType("Success"); + successResult.setType(SUCCESS); try (MockedStatic obDalMock = mockStatic(OBDal.class); MockedStatic requestContextMock = mockStatic(RequestContext.class)) { @@ -249,15 +285,19 @@ public void testPreRunWithLockedInvoice() throws Exception { doNothing().when(mockOBDal).save(any()); doNothing().when(mockOBDal).flush(); - doReturn(mockInvoices).when(processInvoices).getInputContents(any()); + // Use reflection for getInputContents + when(getInputContentsMethod.invoke(processInvoices, Invoice.class)) + .thenReturn(mockInvoices); doReturn(mockData).when(processInvoices).getInput(); + // Rest of the test remains the same when(mockInvoice.isProcessNow()).thenReturn(true); when(mockInvoice.getId()).thenReturn("testId"); requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); - when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)).thenReturn(mockProcessInvoiceUtil); + when(mockWeldUtils.getInstance(ProcessInvoiceUtil.class)) + .thenReturn(mockProcessInvoiceUtil); when(mockProcessInvoiceUtil.process( anyString(), eq("XL"), @@ -275,24 +315,4 @@ public void testPreRunWithLockedInvoice() throws Exception { verify(mockOBDal, times(1)).flush(); } } - - /** - * A testable subclass of ProcessInvoices that exposes certain protected - * or private methods for testing purposes. - */ - public static class TestableProcessInvoices extends ProcessInvoices { - @Override - public Data getInput() { - return super.getInput(); - } - } - - /** - * Verifies that the getInputClass method returns the correct input class - * for processing invoices. - */ - @Test - public void testGetInputClass() { - assertEquals("Should return Invoice.class", Invoice.class, processInvoices.getInputClass()); - } } \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java b/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java index 1d115213e..46c198c64 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java @@ -36,6 +36,10 @@ @RunWith(MockitoJUnitRunner.class) public class ProcessOrdersDefaultsTest { + public static final String RESULT_SHOULD_NOT_BE_NULL = "Result should not be null"; + public static final String ACTIONS = "actions"; + + @InjectMocks private ProcessOrdersDefaults processOrdersDefaults; @@ -58,8 +62,10 @@ public void setUp() { } /** - * Sets up the test environment before each test case. - * Initializes common mocks and variables required across tests. + * Tests the execution of the process with a single document status ("DR"). + * Mocks necessary components and verifies that the result contains the expected actions. + * + * @throws Exception If an error occurs during test execution. */ @Test public void testExecuteWithSingleDocumentStatus() throws Exception { @@ -93,9 +99,9 @@ public void testExecuteWithSingleDocumentStatus() throws Exception { JSONObject result = processOrdersDefaults.execute(parameters, content); - assertNotNull("Result should not be null", result); - assertTrue("Result should contain actions", result.has("actions")); - JSONArray actions = result.getJSONArray("actions"); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertTrue("Result should contain actions", result.has(ACTIONS)); + JSONArray actions = result.getJSONArray(ACTIONS); assertEquals("Should have one action", 1, actions.length()); assertEquals("Should have correct action", "CO", actions.getString(0)); } @@ -154,9 +160,9 @@ public void testExecuteWithMultipleDocumentStatuses() throws Exception { JSONObject result = processOrdersDefaults.execute(parameters, content); - assertNotNull("Result should not be null", result); - assertTrue("Result should contain actions", result.has("actions")); - JSONArray actions = result.getJSONArray("actions"); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertTrue("Result should contain actions", result.has(ACTIONS)); + JSONArray actions = result.getJSONArray(ACTIONS); assertEquals("Should have two actions", 2, actions.length()); assertEquals("First action should be CO", "CO", actions.getString(0)); assertEquals("Second action should be CL", "CL", actions.getString(1)); @@ -193,7 +199,7 @@ public void testGetDocumentActionList() { mockConnectionProvider ); - assertNotNull("Result should not be null", result); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); assertEquals("Should have one action", 1, result.size()); assertEquals("Should have correct action", "CO", result.get(0)); } diff --git a/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java b/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java index 072e1cc22..53f9ca5de 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java @@ -2,18 +2,12 @@ import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -import static org.mockito.Mockito.doReturn; import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; -import org.apache.commons.lang.mutable.MutableBoolean; -import org.codehaus.jettison.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -30,8 +24,6 @@ import org.openbravo.model.common.order.Order; import org.openbravo.service.db.DalConnectionProvider; -import com.smf.jobs.ActionResult; -import com.smf.jobs.Result; /** * Unit tests for the {@code ProcessOrders} class. @@ -42,6 +34,8 @@ @RunWith(MockitoJUnitRunner.class) public class ProcessOrdersTest { + public static final String SUCCESS = "Success"; + @Spy @InjectMocks private ProcessOrders processOrders; @@ -77,6 +71,7 @@ public void setUp() throws Exception { String.class ); processOrderMethod.setAccessible(true); + } /** @@ -90,7 +85,7 @@ public void testProcessOrder() throws Exception { String orderId = "test-order-id"; String docAction = "CO"; OBError expectedResult = new OBError(); - expectedResult.setType("Success"); + expectedResult.setType(SUCCESS); expectedResult.setMessage("Order processed successfully"); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { @@ -111,7 +106,7 @@ public void testProcessOrder() throws Exception { docAction ); - assertEquals("Should return success type", "Success", result.getType()); + assertEquals("Should return success type", SUCCESS, result.getType()); assertEquals( "Should return correct message", "Order processed successfully", @@ -120,57 +115,6 @@ public void testProcessOrder() throws Exception { } } - /** - * Verifies the successful execution of the {@code action} method when - * valid orders and parameters are provided. - * - * @throws Exception If the processing fails unexpectedly. - */ - @Test - public void testActionWithSuccessfulProcessing() throws Exception { - JSONObject parameters = new JSONObject(); - parameters.put("DocAction", "CO"); - MutableBoolean isStopped = new MutableBoolean(false); - - List mockOrders = Arrays.asList(mockOrder); - OBError successResult = new OBError(); - successResult.setType("Success"); - - doReturn(mockOrders).when(processOrders).getInputContents(any()); - - try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { - requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); - when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); - when(mockWeldUtils.getInstance(ProcessOrderUtil.class)).thenReturn(mockOrderUtil); - when(mockOrder.getId()).thenReturn("testId"); - when(mockOrderUtil.process( - anyString(), - anyString(), - any(VariablesSecureApp.class), - any(DalConnectionProvider.class) - )).thenReturn(successResult); - - ActionResult result = processOrders.action(parameters, isStopped); - - assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); - } - } - - /** - * Tests the {@code action} method to ensure it correctly handles a scenario - * where no valid input orders are provided, returning an error result. - */ - @Test - public void testActionWithError() { - JSONObject parameters = new JSONObject(); - MutableBoolean isStopped = new MutableBoolean(false); - - doReturn(List.of()).when(processOrders).getInputContents(any()); - - ActionResult result = processOrders.action(parameters, isStopped); - - assertEquals("Should return error type", Result.Type.ERROR, result.getType()); - } /** * Validates the correct input class type returned by the {@code getInputClass} method. diff --git a/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java b/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java index b5873119e..249708a99 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java @@ -53,6 +53,15 @@ @RunWith(MockitoJUnitRunner.Silent.class) public class ProcessShipmentTest { + public static final String SUCCESS = "Success"; + public static final String TEST_MESSAGE = "Test message"; + public static final String SHIPMENT_PROCESSED_SUCCESSFULLY = "Shipment processed successfully"; + public static final String RESULT_SHOULD_NOT_BE_NULL = "Result should not be null"; + public static final String SHOULD_RETURN_SUCCESS_TYPE = "Should return success type"; + public static final String DOC_ACTION = "DocAction"; + + + /** * A testable subclass of {@code ProcessShipment} that exposes methods for testing. */ @@ -91,6 +100,7 @@ public Data getInput() { private Data mockData; private Method processShipmentMethod; + private Method getInputContentsMethod; /** * Initializes test dependencies and configurations, such as static mocks @@ -106,11 +116,18 @@ public void setUp() throws Exception { ); processShipmentMethod.setAccessible(true); + // Add reflection setup for getInputContents + getInputContentsMethod = com.smf.jobs.Action.class.getDeclaredMethod( + "getInputContents", + Class.class + ); + getInputContentsMethod.setAccessible(true); + try (MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { messageMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn("Test message"); + .thenReturn(TEST_MESSAGE); messageMock.when(() -> OBMessageUtils.parseTranslation(anyString(), any())) - .thenReturn("Test message"); + .thenReturn(TEST_MESSAGE); } } @@ -125,8 +142,8 @@ public void testProcessShipmentPrivateMethod() throws Exception { String shipmentId = "test-shipment-id"; String docAction = "CO"; OBError expectedResult = new OBError(); - expectedResult.setType("Success"); - expectedResult.setMessage("Shipment processed successfully"); + expectedResult.setType(SUCCESS); + expectedResult.setMessage(SHIPMENT_PROCESSED_SUCCESSFULLY); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); @@ -146,11 +163,11 @@ public void testProcessShipmentPrivateMethod() throws Exception { docAction ); - assertNotNull("Result should not be null", result); - assertEquals("Should return success type", "Success", result.getType()); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); assertEquals( "Should return correct message", - "Shipment processed successfully", + SHIPMENT_PROCESSED_SUCCESSFULLY, result.getMessage() ); } @@ -164,13 +181,13 @@ public void testProcessShipmentPrivateMethod() throws Exception { @Test public void testActionWithSuccessfulProcessing() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put("DocAction", "CO"); + parameters.put(DOC_ACTION, "CO"); MutableBoolean isStopped = new MutableBoolean(false); List mockShipments = List.of(mockShipment); OBError successResult = new OBError(); - successResult.setType("Success"); - successResult.setMessage("Shipment processed successfully"); + successResult.setType(SUCCESS); + successResult.setMessage(SHIPMENT_PROCESSED_SUCCESSFULLY); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); @@ -184,13 +201,15 @@ public void testActionWithSuccessfulProcessing() throws Exception { any(DalConnectionProvider.class) )).thenReturn(successResult); - doReturn(mockShipments).when(processShipment).getInputContents(any()); + // Use reflection instead of doReturn + when(getInputContentsMethod.invoke(processShipment, ShipmentInOut.class)) + .thenReturn(mockShipments); doReturn(mockData).when(processShipment).getInput(); ActionResult result = processShipment.action(parameters, isStopped); - assertNotNull("Result should not be null", result); - assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); verify(mockProcessShipmentUtil, times(1)).process( anyString(), anyString(), @@ -203,15 +222,17 @@ public void testActionWithSuccessfulProcessing() throws Exception { /** * Tests the {@code action} method to ensure it handles errors appropriately * when an unexpected condition occurs during shipment processing. + * @throws Exception If processing fails. */ @Test - public void testActionWithError() { + public void testActionWithError() throws Exception { JSONObject parameters = new JSONObject(); MutableBoolean isStopped = new MutableBoolean(false); List mockShipments = List.of(mockShipment); - doReturn(mockShipments).when(processShipment).getInputContents(any()); + when(getInputContentsMethod.invoke(processShipment, ShipmentInOut.class)) + .thenReturn(mockShipments); ActionResult result = processShipment.action(parameters, isStopped); @@ -226,16 +247,18 @@ public void testActionWithError() { @Test public void testActionWithEmptyInput() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put("DocAction", "CO"); + parameters.put(DOC_ACTION, "CO"); MutableBoolean isStopped = new MutableBoolean(false); List emptyShipments = Collections.emptyList(); - doReturn(emptyShipments).when(processShipment).getInputContents(any()); + + when(getInputContentsMethod.invoke(processShipment, ShipmentInOut.class)) + .thenReturn(emptyShipments); doReturn(mockData).when(processShipment).getInput(); ActionResult result = processShipment.action(parameters, isStopped); - assertNotNull("Result should not be null", result); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); assertEquals("Should return success type for empty input", Result.Type.SUCCESS, result.getType()); } @@ -251,8 +274,8 @@ public void testProcessShipment() throws Exception { String shipmentId = "test-shipment-id"; String docAction = "CO"; OBError expectedResult = new OBError(); - expectedResult.setType("Success"); - expectedResult.setMessage("Shipment processed successfully"); + expectedResult.setType(SUCCESS); + expectedResult.setMessage(SHIPMENT_PROCESSED_SUCCESSFULLY); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); @@ -272,8 +295,8 @@ public void testProcessShipment() throws Exception { docAction ); - assertNotNull("Result should not be null", result); - assertEquals("Should return success type", "Success", result.getType()); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); } } @@ -305,7 +328,7 @@ public void testProcessShipmentWithNullShipment() throws Exception { @Test public void testActionWithInvalidDocAction() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put("DocAction", "INVALID_ACTION"); + parameters.put(DOC_ACTION, "INVALID_ACTION"); MutableBoolean isStopped = new MutableBoolean(false); List mockShipments = List.of(mockShipment); @@ -328,9 +351,11 @@ public void testActionWithInvalidDocAction() throws Exception { )).thenReturn(errorResult); messageMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn("Test message"); + .thenReturn(TEST_MESSAGE); - doReturn(mockShipments).when(processShipment).getInputContents(any()); + // Replace doReturn with reflection-based mocking + when(getInputContentsMethod.invoke(processShipment, ShipmentInOut.class)) + .thenReturn(mockShipments); doReturn(mockData).when(processShipment).getInput(); ActionResult result = processShipment.action(parameters, isStopped); @@ -347,7 +372,7 @@ public void testActionWithInvalidDocAction() throws Exception { @Test public void testActionWithMultipleShipments() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put("DocAction", "CO"); + parameters.put(DOC_ACTION, "CO"); MutableBoolean isStopped = new MutableBoolean(false); ShipmentInOut mockShipment2 = mock(ShipmentInOut.class); @@ -355,7 +380,7 @@ public void testActionWithMultipleShipments() throws Exception { List multipleShipments = Arrays.asList(mockShipment, mockShipment2, mockShipment3); OBError successResult = new OBError(); - successResult.setType("Success"); + successResult.setType(SUCCESS); try (MockedStatic requestContextMock = mockStatic(RequestContext.class); MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { @@ -376,15 +401,17 @@ public void testActionWithMultipleShipments() throws Exception { )).thenReturn(successResult); messageMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn("Test message"); + .thenReturn(TEST_MESSAGE); - doReturn(multipleShipments).when(processShipment).getInputContents(any()); + // Replace doReturn with reflection-based mocking + when(getInputContentsMethod.invoke(processShipment, ShipmentInOut.class)) + .thenReturn(multipleShipments); doReturn(mockData).when(processShipment).getInput(); ActionResult result = processShipment.action(parameters, isStopped); - assertNotNull("Result should not be null", result); - assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); verify(mockProcessShipmentUtil, times(3)).process( anyString(), anyString(), @@ -401,6 +428,4 @@ public void testActionWithMultipleShipments() throws Exception { public void testGetInputClass() { assertEquals("Should return ShipmentInOut.class", ShipmentInOut.class, processShipment.getInputClass()); } - - } \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java index f7fdbc2d4..082770682 100644 --- a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java +++ b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java @@ -16,18 +16,42 @@ import com.smf.jobs.ActionResult; import com.smf.jobs.Result; +/** + * Unit tests for the {@link CreateFromOrder} class. + * + *

This test class verifies the behavior of the {@code action} method and the + * {@code getInputClass} method in the {@code CreateFromOrder} class, ensuring + * expected outputs and proper functionality. + */ @RunWith(MockitoJUnitRunner.class) public class CreateFromOrderTest { + /** + * A spy on the {@link CreateFromOrder} class to partially mock its behavior + * while testing its real implementations. + */ @Spy @InjectMocks private CreateFromOrder createFromOrder; - + /** + * Sets up the test environment before each test case. + * + *

Currently, no explicit initialization is required. + */ @Before public void setUp() { + // Setup tasks (currently empty as no explicit initialization is needed) } + /** + * Tests the {@code action} method when the button value is "REFRESH". + * + *

Validates that the method correctly processes the "REFRESH" action, returning + * a non-null {@link ActionResult} of type {@link Result.Type#SUCCESS}. + * + * @throws Exception if any JSON processing errors occur. + */ @Test public void testActionWithRefreshButton() throws Exception { JSONObject parameters = new JSONObject(); @@ -40,6 +64,11 @@ public void testActionWithRefreshButton() throws Exception { assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); } + /** + * Tests the {@code getInputClass} method. + * + *

Ensures that the method correctly returns {@link Order} as the expected input class. + */ @Test public void testGetInputClass() { assertEquals("Should return Order.class", Order.class, createFromOrder.getInputClass()); diff --git a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java index 421b055bc..f8f62ebd2 100644 --- a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java +++ b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java @@ -1,49 +1,89 @@ package com.smf.jobs.defaults.invoices; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +/** + * Unit test class for {@link CreateFromOrdersHQLTransformer}. + * This class contains test cases to verify the behavior of the HQL query transformer + * related to tax inclusion in orders. + * The tests cover various scenarios, including: + *

    + *
  • Query transformation when taxes are included
  • + *
  • Query transformation when taxes are not included
  • + *
  • Handling of missing parameters
  • + *
  • Multiple replacements in the query
  • + *
  • Handling of invalid boolean values
  • + *
  • Management of empty or null queries
  • + *
+ */ @ExtendWith(MockitoExtension.class) public class CreateFromOrdersHQLTransformerTest { + public static final String QUERY_ORDERS_WITHOUT_TAX = "SELECT * FROM Orders WHERE includeTax = 'N'"; + public static final String LINES_INCLUDE_TAXES = "linesIncludeTaxes"; + public static final String TRUE = "true"; + + private CreateFromOrdersHQLTransformer transformer; private String baseHqlQuery; + /** + * Sets up the test environment before each test method. + * Initializes the query transformer and establishes a base query + * to be used in tests. + */ @BeforeEach void setUp() { transformer = new CreateFromOrdersHQLTransformer(); baseHqlQuery = "SELECT * FROM Orders WHERE includeTax = @linesIncludeTaxes@"; } + /** + * Tests HQL query transformation when lines include taxes. + * Verifies that when the 'linesIncludeTaxes' parameter is true, + * the query is correctly transformed by replacing '@linesIncludeTaxes@' with 'Y'. + */ @Test void testTransformHqlQueryWhenLinesIncludeTaxesIsTrue() { Map requestParameters = new HashMap<>(); - requestParameters.put("linesIncludeTaxes", "true"); + requestParameters.put(LINES_INCLUDE_TAXES, TRUE); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'Y'", result); + Assertions.assertEquals("SELECT * FROM Orders WHERE includeTax = 'Y'", result); } + /** + * Tests HQL query transformation when lines do not include taxes. + * Verifies that when the 'linesIncludeTaxes' parameter is false, + * the query is correctly transformed by replacing '@linesIncludeTaxes@' with 'N'. + */ @Test void testTransformHqlQueryWhenLinesIncludeTaxesIsFalse() { Map requestParameters = new HashMap<>(); - requestParameters.put("linesIncludeTaxes", "false"); + requestParameters.put(LINES_INCLUDE_TAXES, "false"); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + Assertions.assertEquals(QUERY_ORDERS_WITHOUT_TAX, result); } + /** + * Tests HQL query transformation when the 'linesIncludeTaxes' parameter is missing. + * Ensures that when no parameter is provided, the query defaults to 'N' + * for tax inclusion. + */ @Test void testTransformHqlQueryWhenLinesIncludeTaxesParameterIsMissing() { Map requestParameters = new HashMap<>(); @@ -51,52 +91,71 @@ void testTransformHqlQueryWhenLinesIncludeTaxesParameterIsMissing() { String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + Assertions.assertEquals(QUERY_ORDERS_WITHOUT_TAX, result); } + /** + * Tests HQL query transformation with multiple replacements. + * Verifies that when multiple occurrences of '@linesIncludeTaxes@' + * are present in the query, they are all correctly replaced. + */ @Test void testTransformHqlQueryWithMultipleReplacements() { String queryWithMultipleReplacements = "SELECT * FROM Orders WHERE includeTax = @linesIncludeTaxes@ AND otherField = @linesIncludeTaxes@"; Map requestParameters = new HashMap<>(); - requestParameters.put("linesIncludeTaxes", "true"); + requestParameters.put(LINES_INCLUDE_TAXES, TRUE); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(queryWithMultipleReplacements, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'Y' AND otherField = 'Y'", result); + Assertions.assertEquals("SELECT * FROM Orders WHERE includeTax = 'Y' AND otherField = 'Y'", result); } + /** + * Tests HQL query transformation with an invalid boolean value. + * Checks that when an invalid boolean value is provided, + * the query defaults to 'N' for tax inclusion. + */ @Test void testTransformHqlQueryWithInvalidBooleanValue() { Map requestParameters = new HashMap<>(); - requestParameters.put("linesIncludeTaxes", "invalid_boolean"); + requestParameters.put(LINES_INCLUDE_TAXES, "invalid_boolean"); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + Assertions.assertEquals(QUERY_ORDERS_WITHOUT_TAX, result); } + /** + * Tests HQL query transformation with an empty query. + * Ensures that an empty query remains unchanged during transformation. + */ @Test void testTransformHqlQueryWithEmptyQuery() { Map requestParameters = new HashMap<>(); - requestParameters.put("linesIncludeTaxes", "true"); + requestParameters.put(LINES_INCLUDE_TAXES, TRUE); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery("", requestParameters, queryNamedParameters); - assertEquals("", result); + Assertions.assertEquals("", result); } + /** + * Tests HQL query transformation with a null query. + * Verifies that attempting to transform a null query + * throws a NullPointerException. + */ @Test void testTransformHqlQueryWithNullQuery() { Map requestParameters = new HashMap<>(); - requestParameters.put("linesIncludeTaxes", "true"); + requestParameters.put(LINES_INCLUDE_TAXES, TRUE); Map queryNamedParameters = new HashMap<>(); - assertThrows(NullPointerException.class, () -> { - transformer.transformHqlQuery(null, requestParameters, queryNamedParameters); - }); + assertThrows(NullPointerException.class, () -> + transformer.transformHqlQuery(null, requestParameters, queryNamedParameters) + ); } } \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java index 49bb36b37..f149acaa6 100644 --- a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java @@ -1,13 +1,19 @@ package com.smf.jobs.defaults.offerPick; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; -import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +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 org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,9 +28,26 @@ import org.openbravo.model.pricing.priceadjustment.PriceAdjustment; import org.hibernate.Session; +/** + * Test class for the {@link OfferAddOrg} functionality. + * This class contains unit tests to verify the behavior of the OfferAddOrg class, + * which is responsible for adding organizations to a price adjustment. + * The test cases cover various scenarios including: + *
    + *
  • Adding a single organization to a price adjustment
  • + *
  • Adding multiple organizations to a price adjustment
  • + *
  • Handling invalid JSON input
  • + *
  • Verifying the JSON name retrieval
  • + *
+ * + * The tests use Mockito for mocking dependencies and static method calls. + */ @ExtendWith(MockitoExtension.class) public class OfferAddOrgTest { + private static final String TEST_ID = "testId" ; + + @Mock private OBDal obDal; @@ -42,27 +65,42 @@ public class OfferAddOrgTest { private OfferAddOrg offerAddOrg; + /** + * Sets up the test environment before each test method. + * + * Initializes the OfferAddOrg instance to be tested. + */ @BeforeEach public void setup() { offerAddOrg = new OfferAddOrg(); } + /** + * Tests the doPickAndExecute method with a single organization. + * Verifies that: + *
    + *
  • A single organization can be added to a price adjustment
  • + *
  • The organization filter is correctly configured
  • + *
  • The organization is saved to the database
  • + *
+ * + * @throws JSONException if there's an error creating JSON objects + */ @Test public void testDoPickAndExecuteSingleOrganization() throws JSONException { try (MockedStatic mockedOBDal = mockStatic(OBDal.class); MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { - // Arrange mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); when(obDal.getSession()).thenReturn(session); when(priceAdjustment.getClient()).thenReturn(client); JSONArray selectedLines = new JSONArray(); JSONObject orgJson = new JSONObject(); - orgJson.put("id", "testId"); + orgJson.put("id", TEST_ID); selectedLines.put(orgJson); - when(obDal.getProxy(eq(Organization.ENTITY_NAME), eq("testId"))).thenReturn(organization); + when(obDal.getProxy(eq(Organization.ENTITY_NAME), eq(TEST_ID))).thenReturn(organization); OBProvider obProvider = mock(OBProvider.class); OrganizationFilter mockOrgFilter = mock(OrganizationFilter.class); @@ -70,10 +108,8 @@ public void testDoPickAndExecuteSingleOrganization() throws JSONException { mockedOBProvider.when(OBProvider::getInstance).thenReturn(obProvider); when(obProvider.get(OrganizationFilter.class)).thenReturn(mockOrgFilter); - // Act offerAddOrg.doPickAndExecute(priceAdjustment, selectedLines); - // Assert verify(mockOrgFilter).setActive(true); verify(mockOrgFilter).setClient(client); verify(mockOrgFilter).setOrganization(organization); @@ -82,12 +118,22 @@ public void testDoPickAndExecuteSingleOrganization() throws JSONException { } } + /** + * Tests the doPickAndExecute method with multiple organizations. + * Verifies that: + *
    + *
  • Multiple organizations can be added to a price adjustment
  • + *
  • The correct number of organizations are saved
  • + *
  • The database session is managed appropriately (flushed and cleared)
  • + *
+ * + * @throws JSONException if there's an error creating JSON objects + */ @Test public void testDoPickAndExecuteMultipleOrganizations() throws JSONException { try (MockedStatic mockedOBDal = mockStatic(OBDal.class); MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { - // Arrange mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); when(obDal.getSession()).thenReturn(session); when(priceAdjustment.getClient()).thenReturn(client); @@ -95,7 +141,7 @@ public void testDoPickAndExecuteMultipleOrganizations() throws JSONException { JSONArray selectedLines = new JSONArray(); for (int i = 0; i < 150; i++) { JSONObject orgJson = new JSONObject(); - orgJson.put("id", "testId" + i); + orgJson.put("id", TEST_ID + i); selectedLines.put(orgJson); } @@ -107,20 +153,26 @@ public void testDoPickAndExecuteMultipleOrganizations() throws JSONException { mockedOBProvider.when(OBProvider::getInstance).thenReturn(obProvider); when(obProvider.get(OrganizationFilter.class)).thenReturn(mockOrgFilter); - // Act offerAddOrg.doPickAndExecute(priceAdjustment, selectedLines); - // Assert verify(obDal, times(150)).save(any()); verify(obDal, times(2)).flush(); verify(session, times(2)).clear(); } } + /** + * Tests the doPickAndExecute method with invalid JSON input. + * Verifies that: + *
    + *
  • An invalid JSON input throws a JSONException
  • + *
+ * + * @throws JSONException to be caught and verified by the test + */ @Test public void testDoPickAndExecuteInvalidJSON() throws JSONException { try (MockedStatic mockedOBDal = mockStatic(OBDal.class)) { - // Arrange mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); JSONArray selectedLines = new JSONArray(); @@ -128,15 +180,20 @@ public void testDoPickAndExecuteInvalidJSON() throws JSONException { invalidJson.put("invalid", "value"); selectedLines.put(invalidJson); - - // Act & Assert assertThrows(JSONException.class, () -> offerAddOrg.doPickAndExecute(priceAdjustment, selectedLines)); } } + /** + * Tests the getJSONName method. + * Verifies that: + *
    + *
  • The method returns the correct JSON name "Conforgprocess"
  • + *
+ */ @Test public void testGetJSONName() { - assertEquals("Conforgprocess", offerAddOrg.getJSONName()); + Assertions.assertEquals("Conforgprocess", offerAddOrg.getJSONName()); } } \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java index cae158382..ce0245b31 100644 --- a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java @@ -3,7 +3,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +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 org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; @@ -22,9 +26,19 @@ import org.openbravo.model.pricing.priceadjustment.PriceAdjustment; import org.hibernate.Session; +/** + * Unit tests for the {@link OfferAddProductCategory} class. + * + *

These tests validate the behavior of the {@code doPickAndExecute} method, + * ensuring that product categories are correctly handled and associated with a + * {@link PriceAdjustment} instance in both single and multiple category scenarios. + */ @ExtendWith(MockitoExtension.class) public class OfferAddProductCategoryTest { + private static final String TEST_ID = "testId" ; + + @Mock private OBDal obDal; @@ -42,6 +56,12 @@ public class OfferAddProductCategoryTest { private OfferAddProductCategory offerAddProductCategory; + /** + * Initializes the test environment before each test. + * + *

Configures the {@code OfferAddProductCategory} instance and defines default behavior for + * the mocked objects, such as {@code PriceAdjustment}. + */ @BeforeEach public void setup() { offerAddProductCategory = new OfferAddProductCategory(); @@ -49,22 +69,29 @@ public void setup() { when(priceAdjustment.getOrganization()).thenReturn(organization); } + /** + * Tests the {@code doPickAndExecute} method with a single product category. + * + *

Validates that the method retrieves, sets, and saves a single product category + * and its associated {@link PriceAdjustment}, ensuring the proper calls to mock objects. + * + * @throws JSONException if there is an error creating the JSON input. + */ @Test public void testDoPickAndExecuteSingleProductCategory() throws JSONException { try (MockedStatic mockedOBDal = mockStatic(OBDal.class); MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { - // Arrange mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); when(obDal.getSession()).thenReturn(session); JSONArray selectedLines = new JSONArray(); JSONObject productCatJson = new JSONObject(); - productCatJson.put("id", "testId"); + productCatJson.put("id", TEST_ID); selectedLines.put(productCatJson); ProductCategory productCategory = mock(ProductCategory.class); - when(obDal.getProxy(eq(ProductCategory.ENTITY_NAME), eq("testId"))).thenReturn(productCategory); + when(obDal.getProxy(eq(ProductCategory.ENTITY_NAME), eq(TEST_ID))).thenReturn(productCategory); OBProvider obProvider = mock(OBProvider.class); org.openbravo.model.pricing.priceadjustment.ProductCategory mockProductCategory = @@ -74,10 +101,8 @@ public void testDoPickAndExecuteSingleProductCategory() throws JSONException { when(obProvider.get(org.openbravo.model.pricing.priceadjustment.ProductCategory.class)) .thenReturn(mockProductCategory); - // Act offerAddProductCategory.doPickAndExecute(priceAdjustment, selectedLines); - // Assert verify(mockProductCategory).setActive(true); verify(mockProductCategory).setClient(client); verify(mockProductCategory).setOrganization(organization); @@ -87,19 +112,26 @@ public void testDoPickAndExecuteSingleProductCategory() throws JSONException { } } + /** + * Tests the {@code doPickAndExecute} method with multiple product categories. + * + *

Validates that the method efficiently processes and saves multiple product categories, + * flushes the session at regular intervals, and clears it to optimize performance. + * + * @throws JSONException if there is an error creating the JSON input. + */ @Test public void testDoPickAndExecuteMultipleProductCategories() throws JSONException { try (MockedStatic mockedOBDal = mockStatic(OBDal.class); MockedStatic mockedOBProvider = mockStatic(OBProvider.class)) { - // Arrange mockedOBDal.when(OBDal::getInstance).thenReturn(obDal); when(obDal.getSession()).thenReturn(session); JSONArray selectedLines = new JSONArray(); for (int i = 0; i < 150; i++) { JSONObject productCatJson = new JSONObject(); - productCatJson.put("id", "testId" + i); + productCatJson.put("id", TEST_ID + i); selectedLines.put(productCatJson); } @@ -114,10 +146,8 @@ public void testDoPickAndExecuteMultipleProductCategories() throws JSONException when(obProvider.get(org.openbravo.model.pricing.priceadjustment.ProductCategory.class)) .thenReturn(mockProductCategory); - // Act offerAddProductCategory.doPickAndExecute(priceAdjustment, selectedLines); - // Assert verify(obDal, times(150)).save(any()); verify(obDal, times(2)).flush(); verify(session, times(2)).clear(); diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java index 7e222f5ee..fdfe4505a 100644 --- a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java @@ -1,14 +1,23 @@ package com.smf.jobs.defaults.offerPick; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; - +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +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 org.apache.commons.lang.StringUtils; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.hibernate.Session; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -117,7 +126,7 @@ public void testDoPickAndExecute() throws Exception { */ @Test public void testGetJSONName() { - assert "Confprodprocess".equals(offerAddProduct.getJSONName()); + Assert.assertEquals("Confprodprocess", StringUtils.defaultString(offerAddProduct.getJSONName())); } /** diff --git a/src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java b/src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java index 65b67f454..a227b66f0 100644 --- a/src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java +++ b/src-test/src/com/smf/jobs/defaults/provider/JobsComponentProviderTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; @@ -93,13 +94,13 @@ public void testGetGlobalComponentResources() { for (Object resource : globalResources) { String resourceString = resource.toString(); - if (resourceString.contains("processRecords.js")) { + if (StringUtils.contains(resourceString, "processRecords.js")) { hasProcessRecordsJs = true; } - if (resourceString.contains("ob-clone-record.js")) { + if (StringUtils.contains(resourceString, "ob-clone-record.js")) { hasCloneRecordJs = true; } - if (resourceString.contains("createFromOrders.js")) { + if (StringUtils.contains(resourceString, "createFromOrders.js")) { hasCreateFromOrdersJs = true; } } diff --git a/src-test/src/com/smf/test/CoreTestSuite.java b/src-test/src/com/smf/test/CoreTestSuite.java new file mode 100644 index 000000000..c05ece513 --- /dev/null +++ b/src-test/src/com/smf/test/CoreTestSuite.java @@ -0,0 +1,69 @@ +package com.smf.test; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +import com.smf.jobs.defaults.CloneOrderHookTest; +import com.smf.jobs.defaults.ProcessInvoicesTest; +import com.smf.jobs.defaults.ProcessOrdersDefaultsTest; +import com.smf.jobs.defaults.ProcessOrdersTest; +import com.smf.jobs.defaults.ProcessShipmentTest; +import com.smf.jobs.defaults.invoices.CreateFromOrderTest; +import com.smf.jobs.defaults.invoices.CreateFromOrdersHQLTransformerTest; +import com.smf.jobs.defaults.offerPick.OfferAddOrgTest; +import com.smf.jobs.defaults.offerPick.OfferAddProductCategoryTest; +import com.smf.jobs.defaults.offerPick.OfferAddProductTest; +import com.smf.jobs.defaults.provider.JobsComponentProviderTest; + +/** + * Test suite to run all unit tests for the SMF Jobs defaults module. + *

+ * This suite includes tests for core functionalities such as order processing, + * invoice creation, shipment processing, and offer handling. + *

+ * + *

JUnit {@link Suite} is used to group related test classes and execute them together.

+ * + *

Test Classes Included

+ *
    + *
  • {@link CreateFromOrdersHQLTransformerTest}
  • + *
  • {@link CreateFromOrderTest}
  • + *
  • {@link OfferAddOrgTest}
  • + *
  • {@link OfferAddProductCategoryTest}
  • + *
  • {@link OfferAddProductTest}
  • + *
  • {@link JobsComponentProviderTest}
  • + *
  • {@link CloneOrderHookTest}
  • + *
  • {@link ProcessInvoicesTest}
  • + *
  • {@link ProcessOrdersDefaultsTest}
  • + *
  • {@link ProcessOrdersTest}
  • + *
  • {@link ProcessShipmentTest}
  • + *
+ */ +@RunWith(Suite.class) +@Suite.SuiteClasses({ + + // SMF Jobs defaults + CreateFromOrdersHQLTransformerTest.class, + CreateFromOrderTest.class, + OfferAddOrgTest.class, + OfferAddProductCategoryTest.class, + OfferAddProductTest.class, + JobsComponentProviderTest.class, + CloneOrderHookTest.class, + ProcessInvoicesTest.class, + ProcessOrdersDefaultsTest.class, + ProcessOrdersTest.class, + ProcessShipmentTest.class + +}) + +public class CoreTestSuite { + /** + * The CoreTestSuite class is used as an entry point to run all + * the unit tests in the SMF Jobs defaults module. + *

+ * No additional logic is required in this class, as it serves as a container + * for the list of test classes defined in the {@code @SuiteClasses} annotation. + *

+ */ +} From 76d808d2adf928a822e8acd0a1edbb48d5e08ac5 Mon Sep 17 00:00:00 2001 From: Emi-Polliotti Date: Wed, 18 Dec 2024 09:35:54 -0300 Subject: [PATCH 4/4] Feature ETP-870: Refactored constants into a utility class --- .../handler/CostingRuleUtilsTest.java | 30 ++++---- ...ReportValuationStockAddParametersTest.java | 16 ++--- .../ReportValuationStockBuildDataTest.java | 28 +++----- .../ReportValuationStockGetReportTest.java | 54 +++++---------- .../ReportValuationStockParametersTest.java | 4 +- .../ReportValuationStockPrintTest.java | 69 ++++++++----------- .../ReportValuationStockSummaryTest.java | 43 +++++------- .../ReportValuationStockWarehousesTest.java | 27 +++----- .../handler/TestUtils.java | 65 +++++++++++++++++ .../smf/jobs/defaults/CloneOrderHookTest.java | 4 +- .../jobs/defaults/ProcessInvoicesTest.java | 17 ++--- .../defaults/ProcessOrdersDefaultsTest.java | 41 +++++------ .../smf/jobs/defaults/ProcessOrdersTest.java | 8 +-- .../jobs/defaults/ProcessShipmentTest.java | 65 ++++++++--------- .../src/com/smf/jobs/defaults/Utility.java | 39 +++++++++++ .../invoices/CreateFromOrderTest.java | 5 +- .../CreateFromOrdersHQLTransformerTest.java | 25 +++---- .../defaults/offerPick/OfferAddOrgTest.java | 10 +-- .../OfferAddProductCategoryTest.java | 10 +-- 19 files changed, 301 insertions(+), 259 deletions(-) create mode 100644 src-test/src/com/etendoerp/reportvaluationstock/handler/TestUtils.java create mode 100644 src-test/src/com/smf/jobs/defaults/Utility.java diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java index 5ce46d855..e7a4521ee 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/CostingRuleUtilsTest.java @@ -1,5 +1,6 @@ package com.etendoerp.reportvaluationstock.handler; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -13,8 +14,6 @@ import org.mockito.Mockito; import org.openbravo.model.materialmgmt.cost.CostingRule; -import java.lang.reflect.Method; - /** * Test class for CostingRuleUtils, which verifies the logic related * to the calculation of costing rules based on organizations. @@ -23,7 +22,7 @@ public class CostingRuleUtilsTest { private Organization mockOrganization; private OBDal mockOBDal; - private Method getLEsCostingAlgortithmMethod; + private ReportValuationStock reportValuationStock; /** * Sets up the initial state required for the tests. Prepare mocks and retrieves @@ -33,8 +32,7 @@ public class CostingRuleUtilsTest { */ @Before public void setUp() throws Exception { - getLEsCostingAlgortithmMethod = ReportValuationStock.class.getDeclaredMethod("getLEsCostingAlgortithm", Organization.class); - getLEsCostingAlgortithmMethod.setAccessible(true); + reportValuationStock = new ReportValuationStock(); mockOrganization = Mockito.mock(Organization.class); mockOBDal = Mockito.mock(OBDal.class); @@ -56,18 +54,20 @@ public void testGetLEsCostingAlgortithmWithValidOrganization() throws Exception try (MockedStatic mockedStatic = Mockito.mockStatic(OBDal.class)) { mockedStatic.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); + @SuppressWarnings("unchecked") OBQuery mockQuery = Mockito.mock(OBQuery.class); + Mockito.when(mockOBDal.createQuery(Mockito.eq(CostingRule.class), Mockito.anyString())) .thenReturn(mockQuery); - Mockito.when(mockQuery.setNamedParameter(Mockito.eq("orgId"), Mockito.eq(orgId))) + Mockito.when(mockQuery.setNamedParameter(Mockito.anyString(), Mockito.any())) .thenReturn(mockQuery); Mockito.when(mockQuery.setMaxResult(1)).thenReturn(mockQuery); Mockito.when(mockQuery.uniqueResult()).thenReturn(expectedRule); - CostingRule result = (CostingRule) getLEsCostingAlgortithmMethod.invoke(null, mockOrganization); + CostingRule result = reportValuationStock.getLEsCostingAlgortithm(mockOrganization); - assertNotNull("El resultado no debería ser null", result); - assertEquals("El resultado debería ser el CostingRule esperado", expectedRule, result); + assertNotNull("The result should not be null", result); + assertEquals("The result should be the expected CostingRule", expectedRule, result); } } @@ -86,17 +86,19 @@ public void testGetLEsCostingAlgortithmNoRulesFound() throws Exception { try (MockedStatic mockedStatic = Mockito.mockStatic(OBDal.class)) { mockedStatic.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); - OBQuery mockQuery = Mockito.mock(OBQuery.class); + @SuppressWarnings("unchecked") + OBQuery mockQuery = Mockito.mock(OBQuery.class); + Mockito.when(mockOBDal.createQuery(Mockito.eq(CostingRule.class), Mockito.anyString())) .thenReturn(mockQuery); - Mockito.when(mockQuery.setNamedParameter(Mockito.eq("orgId"), Mockito.eq(orgId))) + Mockito.when(mockQuery.setNamedParameter(Mockito.anyString(), Mockito.any())) .thenReturn(mockQuery); Mockito.when(mockQuery.setMaxResult(1)).thenReturn(mockQuery); Mockito.when(mockQuery.uniqueResult()).thenReturn(null); - CostingRule result = (CostingRule) getLEsCostingAlgortithmMethod.invoke(null, mockOrganization); + CostingRule result = reportValuationStock.getLEsCostingAlgortithm(mockOrganization); - assertNull("El resultado debería ser null cuando no se encuentran reglas", result); + assertNull("The result should be null when no rules are found", result); } } -} +} \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java index db393b0ae..cf2f7afd0 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java @@ -71,11 +71,7 @@ public class ReportValuationStockAddParametersTest { private ReportValuationStock reportValuationStock; - private static final String TEST_ORG_ID = "testOrgId"; - private static final String TEST_WAREHOUSE_ID = "testWarehouseId"; - private static final String TEST_CATEGORY_ID = "testCategoryId"; - private static final String TEST_CURRENCY_ID = "testCurrencyId"; - private static final String TEST_DATE = "2024-01-01"; + /** * Set up the test environment, including mocks and static contexts. @@ -146,12 +142,12 @@ public void testAddAdditionalParametersValidInput() throws Exception { JSONObject jsonContent = new JSONObject(); JSONObject params = new JSONObject(); - params.put("AD_Org_ID", TEST_ORG_ID); - params.put("M_Warehouse_ID", TEST_WAREHOUSE_ID); + params.put("AD_Org_ID", TestUtils.TEST_ORG_ID); + params.put("M_Warehouse_ID", TestUtils.TEST_WAREHOUSE_ID); params.put("WarehouseConsolidation", true); - params.put("M_Product_Category_ID", TEST_CATEGORY_ID); - params.put("C_Currency_ID", TEST_CURRENCY_ID); - params.put("Date", TEST_DATE); + params.put("M_Product_Category_ID", TestUtils.TEST_CATEGORY_ID); + params.put("C_Currency_ID", TestUtils.TEST_CURRENCY_ID); + params.put("Date", TestUtils.TEST_DATE); jsonContent.put("_params", params); jsonContent.put(ApplicationConstants.BUTTON_VALUE, "PDF"); diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java index 7e19ef938..94f9727c7 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockBuildDataTest.java @@ -65,13 +65,7 @@ public class ReportValuationStockBuildDataTest { private OrganizationStructureProvider mockOsp; private Method buildDataMethod; - private static final String TEST_DATE = "2024-01-01"; - private static final String TEST_ORG_ID = "testOrgId"; - private static final String TEST_WAREHOUSE_ID = "testWarehouseId"; - private static final String TEST_CATEGORY_ID = "testCategoryId"; - private static final String TEST_CURRENCY_ID = "testCurrencyId"; - private static final String TEST_CLIENT_ID = "testClientId"; - private static final String WAREHOUSE_NOT_IN_LE = "WarehouseNotInLE"; + /** @@ -95,10 +89,10 @@ public void setUp() throws Exception { ); buildDataMethod.setAccessible(true); - when(mockClient.getId()).thenReturn(TEST_CLIENT_ID); + when(mockClient.getId()).thenReturn(TestUtils.TEST_CLIENT_ID); Set orgTree = new HashSet<>(); - orgTree.add(TEST_ORG_ID); + orgTree.add(TestUtils.TEST_ORG_ID); } /** @@ -130,9 +124,9 @@ public void testBuildDataWithNullLegalEntity() { when(mockOsp.getLegalEntity(any(Organization.class))).thenReturn(null); OBError mockError = mock(OBError.class); - when(mockError.getMessage()).thenReturn(WAREHOUSE_NOT_IN_LE); + when(mockError.getMessage()).thenReturn(TestUtils.WAREHOUSE_NOT_IN_LE); obMessageUtilsMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn(WAREHOUSE_NOT_IN_LE); + .thenReturn(TestUtils.WAREHOUSE_NOT_IN_LE); obMessageUtilsMock.when(() -> OBMessageUtils.translateError(anyString())) .thenReturn(mockError); @@ -140,18 +134,18 @@ public void testBuildDataWithNullLegalEntity() { buildDataMethod.invoke( reportValuationStock, vars, - TEST_DATE, - TEST_ORG_ID, - TEST_WAREHOUSE_ID, - TEST_CATEGORY_ID, - TEST_CURRENCY_ID, + TestUtils.TEST_DATE, + TestUtils.TEST_ORG_ID, + TestUtils.TEST_WAREHOUSE_ID, + TestUtils.TEST_CATEGORY_ID, + TestUtils.TEST_CURRENCY_ID, false, parameters ); } catch (Exception e) { assertTrue("Expected ServletException", e.getCause() instanceof ServletException); assertTrue("Expected correct error message", - StringUtils.contains(e.getCause().getMessage(), WAREHOUSE_NOT_IN_LE)); + StringUtils.contains(e.getCause().getMessage(), TestUtils.WAREHOUSE_NOT_IN_LE)); } } } diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java index d3cce1db6..a83c8468a 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java @@ -36,8 +36,6 @@ @RunWith(MockitoJUnitRunner.class) public class ReportValuationStockGetReportTest { - private static final String PROCESS_TIME = "processTime"; - @Mock private VariablesSecureApp vars; @@ -56,21 +54,7 @@ public class ReportValuationStockGetReportTest { private ReportValuationStock reportValuationStock; private Method getReportValuationStockDataMethod; - private static final String TEST_DATE = "2024-01-01"; - private static final String TEST_CATEGORY = "TEST_CATEGORY"; - private static final String TEST_CURRENCY = "102"; - private static final String TEST_WAREHOUSE = "TEST_WAREHOUSE"; - private static final String TEST_ORG = "TEST_ORG"; - private static final String TEST_CLIENT = "TEST_CLIENT"; - private static final String TEST_LANGUAGE = "en_US"; - private static final String DATE_NEXT = "dateNext"; - private static final String MAX_AGG_DATE = "maxAggDate"; - private static final String DATE_FORMAT = "dateFormat"; - private static final String ORG_IDS = "orgIds"; - private static final String ERROR_RESULT_NULL = "Result should not be null"; - private static final String ERROR_DATA_LENGTH = "Should return expected data length"; - private static final String ERROR_EXPECTED_DATA = "Should return expected data"; /** @@ -92,7 +76,7 @@ public void setUp() throws Exception { ); getReportValuationStockDataMethod.setAccessible(true); - when(vars.getLanguage()).thenReturn(TEST_LANGUAGE); + when(vars.getLanguage()).thenReturn(TestUtils.TEST_LANGUAGE); } /** @@ -115,14 +99,14 @@ public void testGetReportDataWithCostTypeAndNoWarehouseConsolidation() throws Ex ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( reportValuationStock, - vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, PROCESS_TIME, - "N", "STA", TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, - ORG_IDS, TEST_ORG, TEST_CLIENT, DATE_NEXT, MAX_AGG_DATE, DATE_FORMAT + vars, TestUtils.TEST_DATE, TestUtils.TEST_CATEGORY, TestUtils.TEST_CURRENCY, false, TestUtils.PROCESS_TIME, + "N", "STA", TestUtils.TEST_WAREHOUSE, readOnlyCP, filterOrg, TestUtils.TEST_ORG, + TestUtils.ORG_IDS, TestUtils.TEST_ORG, TestUtils.TEST_CLIENT, TestUtils.DATE_NEXT, TestUtils.MAX_AGG_DATE, TestUtils.DATE_FORMAT ); - assertNotNull(ERROR_RESULT_NULL, result); - assertEquals(ERROR_DATA_LENGTH, expectedData.length, result.length); - assertEquals(ERROR_EXPECTED_DATA, expectedData[0], result[0]); + assertNotNull(TestUtils.ERROR_RESULT_NULL, result); + assertEquals(TestUtils.ERROR_DATA_LENGTH, expectedData.length, result.length); + assertEquals(TestUtils.ERROR_EXPECTED_DATA, expectedData[0], result[0]); } } @@ -145,14 +129,14 @@ public void testGetReportDataWithoutCostTypeAndWithWarehouseConsolidation() thro ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( reportValuationStock, - vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, true, PROCESS_TIME, - "N", null, TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, - ORG_IDS, TEST_ORG, TEST_CLIENT, DATE_NEXT, MAX_AGG_DATE, DATE_FORMAT + vars, TestUtils.TEST_DATE, TestUtils.TEST_CATEGORY, TestUtils.TEST_CURRENCY, true, TestUtils.PROCESS_TIME, + "N", null, TestUtils.TEST_WAREHOUSE, readOnlyCP, filterOrg, TestUtils.TEST_ORG, + TestUtils.ORG_IDS, TestUtils.TEST_ORG, TestUtils.TEST_CLIENT, TestUtils.DATE_NEXT, TestUtils.MAX_AGG_DATE, TestUtils.DATE_FORMAT ); - assertNotNull(ERROR_RESULT_NULL, result); - assertEquals(ERROR_DATA_LENGTH, expectedData.length, result.length); - assertEquals(ERROR_EXPECTED_DATA, expectedData[0], result[0]); + assertNotNull(TestUtils.ERROR_RESULT_NULL, result); + assertEquals(TestUtils.ERROR_DATA_LENGTH, expectedData.length, result.length); + assertEquals(TestUtils.ERROR_EXPECTED_DATA, expectedData[0], result[0]); } } @@ -175,14 +159,14 @@ public void testGetReportDataWithoutCostTypeAndNoWarehouseConsolidation() throws ReportValuationStockData[] result = (ReportValuationStockData[]) getReportValuationStockDataMethod.invoke( reportValuationStock, - vars, TEST_DATE, TEST_CATEGORY, TEST_CURRENCY, false, PROCESS_TIME, - "N", null, TEST_WAREHOUSE, readOnlyCP, filterOrg, TEST_ORG, - ORG_IDS, TEST_ORG, TEST_CLIENT, DATE_NEXT, MAX_AGG_DATE, DATE_FORMAT + vars, TestUtils.TEST_DATE, TestUtils.TEST_CATEGORY, TestUtils.TEST_CURRENCY, false, TestUtils.PROCESS_TIME, + "N", null, TestUtils.TEST_WAREHOUSE, readOnlyCP, filterOrg, TestUtils.TEST_ORG, + TestUtils.ORG_IDS, TestUtils.TEST_ORG, TestUtils.TEST_CLIENT, TestUtils.DATE_NEXT, TestUtils.MAX_AGG_DATE, TestUtils.DATE_FORMAT ); - assertNotNull(ERROR_RESULT_NULL, result); - assertEquals(ERROR_DATA_LENGTH, expectedData.length, result.length); - assertEquals(ERROR_EXPECTED_DATA, expectedData[0], result[0]); + assertNotNull(TestUtils.ERROR_RESULT_NULL, result); + assertEquals(TestUtils.ERROR_DATA_LENGTH, expectedData.length, result.length); + assertEquals(TestUtils.ERROR_EXPECTED_DATA, expectedData[0], result[0]); } } diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java index 25d76d40e..f173e3cb7 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockParametersTest.java @@ -34,8 +34,6 @@ @RunWith(MockitoJUnitRunner.class) public class ReportValuationStockParametersTest { - private static final String TEST_ORG_ID = "testOrgId"; - @Mock private ReportDefinition mockProcess; @@ -109,7 +107,7 @@ public void testAddAdditionalParametersInvalidDate() throws Exception { JSONObject jsonContent = new JSONObject(); JSONObject params = new JSONObject(); - params.put("AD_Org_ID", TEST_ORG_ID); + params.put("AD_Org_ID", TestUtils.TEST_ORG_ID); params.put("Date", "invalid-date"); jsonContent.put("_params", params); diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java index abf17c1dc..7eb1999c4 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockPrintTest.java @@ -45,16 +45,7 @@ public class ReportValuationStockPrintTest { private CostingAlgorithm costingAlgorithm; private Method printReportMethod; - private static final String TEST_DATE = "2024-01-01"; - private static final String TEST_COST_TYPE = "AVA"; - private static final String TEST_ALGORITHM_NAME = "Average Algorithm"; - private static final String TEST_TRANSLATED_HEADER = "Translated Cost Header"; - private static final String TEST_TRANSLATED_VALUATION = "Translated Valuation Header"; - private static final String NUMBER_FORMAT = "#,##0.00"; - private static final String ERROR_PARAMETERS_NULL = "Parameters should not be null"; - private static final String NUMBER_FORMAT_KEY = "NUMBERFORMAT"; - private static final String ERROR_DECIMAL_FORMAT = "Should have correct decimal format"; - private static final String COST_FORMAT_KEY = "COSTFORMAT"; + /** @@ -78,10 +69,10 @@ public void setUp() throws Exception { when(vars.getSessionValue("#AD_ReportDecimalSeparator")).thenReturn("."); when(vars.getSessionValue("#AD_ReportGroupingSeparator")).thenReturn(","); - when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn(NUMBER_FORMAT); + when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn(TestUtils.NUMBER_FORMAT); when(vars.getJavaDateFormat()).thenReturn("yyyy-MM-dd"); - when(costingAlgorithm.getName()).thenReturn(TEST_ALGORITHM_NAME); + when(costingAlgorithm.getName()).thenReturn(TestUtils.TEST_ALGORITHM_NAME); } /** @@ -98,7 +89,7 @@ public void setUp() throws Exception { public void testPrintReportWithCostingAlgorithm() throws Exception { ReportValuationStockData[] testData = new ReportValuationStockData[0]; Map parameters = new HashMap<>(); - DecimalFormat mockFormat = new DecimalFormat(NUMBER_FORMAT); + DecimalFormat mockFormat = new DecimalFormat(TestUtils.NUMBER_FORMAT); try (MockedStatic obMessageUtilsMock = mockStatic(OBMessageUtils.class); MockedStatic utilityMock = mockStatic(Utility.class)) { @@ -108,34 +99,34 @@ public void testPrintReportWithCostingAlgorithm() throws Exception { obMessageUtilsMock.when(() -> OBMessageUtils.messageBD("ValuedStockReport_ValuationHeader")) .thenReturn("Valuation Header @algorithm@"); obMessageUtilsMock.when(() -> OBMessageUtils.parseTranslation(anyString(), any())) - .thenReturn(TEST_TRANSLATED_HEADER) - .thenReturn(TEST_TRANSLATED_VALUATION); + .thenReturn(TestUtils.TEST_TRANSLATED_HEADER) + .thenReturn(TestUtils.TEST_TRANSLATED_VALUATION); utilityMock.when(() -> Utility.getFormat(any(), anyString())).thenReturn(mockFormat); printReportMethod.invoke( reportValuationStock, vars, - TEST_DATE, + TestUtils.TEST_DATE, testData, - TEST_COST_TYPE, + TestUtils.TEST_COST_TYPE, costingAlgorithm, parameters ); - assertNotNull(ERROR_PARAMETERS_NULL, parameters); + assertNotNull(TestUtils.ERROR_PARAMETERS_NULL, parameters); assertEquals("Should have correct cost header", - TEST_TRANSLATED_HEADER, parameters.get("ALG_COST")); + TestUtils.TEST_TRANSLATED_HEADER, parameters.get("ALG_COST")); assertEquals("Should have correct valuation header", - TEST_TRANSLATED_VALUATION, parameters.get("SUM_ALG_COST")); + TestUtils.TEST_TRANSLATED_VALUATION, parameters.get("SUM_ALG_COST")); assertEquals("Should have correct title", "Valued Stock Report", parameters.get("TITLE")); assertEquals("Should have correct date", - TEST_DATE, parameters.get("DATE")); + TestUtils.TEST_DATE, parameters.get("DATE")); assertNotNull("Should have number format", - parameters.get(NUMBER_FORMAT_KEY)); - assertEquals(ERROR_DECIMAL_FORMAT, - mockFormat, parameters.get(COST_FORMAT_KEY)); + parameters.get(TestUtils.NUMBER_FORMAT_KEY)); + assertEquals(TestUtils.ERROR_DECIMAL_FORMAT, + mockFormat, parameters.get(TestUtils.COST_FORMAT_KEY)); } } @@ -153,7 +144,7 @@ public void testPrintReportWithCostingAlgorithm() throws Exception { public void testPrintReportWithoutCostingAlgorithm() throws Exception { ReportValuationStockData[] testData = new ReportValuationStockData[0]; Map parameters = new HashMap<>(); - DecimalFormat mockFormat = new DecimalFormat(NUMBER_FORMAT); + DecimalFormat mockFormat = new DecimalFormat(TestUtils.NUMBER_FORMAT); try (MockedStatic utilityMock = mockStatic(Utility.class)) { utilityMock.when(() -> Utility.getFormat(any(), anyString())).thenReturn(mockFormat); @@ -161,14 +152,14 @@ public void testPrintReportWithoutCostingAlgorithm() throws Exception { printReportMethod.invoke( reportValuationStock, vars, - TEST_DATE, + TestUtils.TEST_DATE, testData, null, null, parameters ); - assertNotNull(ERROR_PARAMETERS_NULL, parameters); + assertNotNull(TestUtils.ERROR_PARAMETERS_NULL, parameters); assertEquals("Should have empty cost header", "", parameters.get("ALG_COST")); assertEquals("Should have empty valuation header", @@ -176,11 +167,11 @@ public void testPrintReportWithoutCostingAlgorithm() throws Exception { assertEquals("Should have correct title", "Valued Stock Report", parameters.get("TITLE")); assertEquals("Should have correct date", - TEST_DATE, parameters.get("DATE")); + TestUtils.TEST_DATE, parameters.get("DATE")); assertNotNull("Should have number format", - parameters.get(NUMBER_FORMAT_KEY)); - assertEquals(ERROR_DECIMAL_FORMAT, - mockFormat, parameters.get(COST_FORMAT_KEY)); + parameters.get(TestUtils.NUMBER_FORMAT_KEY)); + assertEquals(TestUtils.ERROR_DECIMAL_FORMAT, + mockFormat, parameters.get(TestUtils.COST_FORMAT_KEY)); } } @@ -198,11 +189,11 @@ public void testPrintReportWithoutCostingAlgorithm() throws Exception { public void testPrintReportWithCustomFormats() throws Exception { ReportValuationStockData[] testData = new ReportValuationStockData[0]; Map parameters = new HashMap<>(); - DecimalFormat mockFormat = new DecimalFormat("#,##0.000"); + DecimalFormat mockFormat = new DecimalFormat(TestUtils.NUMBER_FORMAT); when(vars.getSessionValue("#AD_ReportDecimalSeparator")).thenReturn(","); when(vars.getSessionValue("#AD_ReportGroupingSeparator")).thenReturn("."); - when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn("#,##0.000"); + when(vars.getSessionValue("#AD_ReportNumberFormat")).thenReturn(TestUtils.NUMBER_FORMAT); try (MockedStatic utilityMock = mockStatic(Utility.class)) { utilityMock.when(() -> Utility.getFormat(any(), anyString())).thenReturn(mockFormat); @@ -210,18 +201,18 @@ public void testPrintReportWithCustomFormats() throws Exception { printReportMethod.invoke( reportValuationStock, vars, - TEST_DATE, + TestUtils.TEST_DATE, testData, - TEST_COST_TYPE, + TestUtils.TEST_COST_TYPE, null, parameters ); - assertNotNull(ERROR_PARAMETERS_NULL, parameters); + assertNotNull(TestUtils.ERROR_PARAMETERS_NULL, parameters); assertNotNull("Should have number format with custom separators", - parameters.get(NUMBER_FORMAT_KEY)); - assertEquals(ERROR_DECIMAL_FORMAT, - mockFormat, parameters.get(COST_FORMAT_KEY)); + parameters.get(TestUtils.NUMBER_FORMAT_KEY)); + assertEquals(TestUtils.ERROR_DECIMAL_FORMAT, + mockFormat, parameters.get(TestUtils.COST_FORMAT_KEY)); } } } \ No newline at end of file diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java index ac827718d..1a432a1f8 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockSummaryTest.java @@ -29,12 +29,7 @@ public class ReportValuationStockSummaryTest { private Method getSummaryProductCategoriesMethod; - private static final String ERROR_RESULT_NULL = "Result should not be null"; - private static final String CATEGORY_NAME = "categoryName"; - private static final String TEST_CATEGORY = "TestCategory"; - private static final String TOTAL_COST = "totalCost"; - private static final String TEST_COST_VALUE = "100.00"; - private static final String ERROR_ONE_CATEGORY = "Should contain one category"; + /** @@ -83,7 +78,7 @@ public void testGetSummaryProductCategoriesWithEmptyData() throws Exception { (Object) data ); - assertNotNull(ERROR_RESULT_NULL, result); + assertNotNull(TestUtils.ERROR_RESULT_NULL, result); assertEquals("Empty data should return empty result", 0, result.length); } @@ -99,8 +94,8 @@ public void testGetSummaryProductCategoriesWithEmptyData() throws Exception { @Test public void testGetSummaryProductCategoriesWithSingleCategory() throws Exception { ReportValuationStockData singleData = new ReportValuationStockData(); - setFieldValue(singleData, CATEGORY_NAME, TEST_CATEGORY); - setFieldValue(singleData, TOTAL_COST, TEST_COST_VALUE); + setFieldValue(singleData, TestUtils.CATEGORY_NAME, TestUtils.TEST_CATEGORY); + setFieldValue(singleData, TestUtils.TOTAL_COST, TestUtils.TEST_COST_VALUE); ReportValuationStockData[] data = new ReportValuationStockData[] { singleData }; @@ -109,11 +104,11 @@ public void testGetSummaryProductCategoriesWithSingleCategory() throws Exception (Object) data ); - assertNotNull(ERROR_RESULT_NULL, result); - assertEquals(ERROR_ONE_CATEGORY, 1, result.length); - assertEquals("Should have correct category name", TEST_CATEGORY, + assertNotNull(TestUtils.ERROR_RESULT_NULL, result); + assertEquals(TestUtils.ERROR_ONE_CATEGORY, 1, result.length); + assertEquals("Should have correct category name", TestUtils.TEST_CATEGORY, result[0].getField("category")); - assertEquals("Should have correct cost", TEST_COST_VALUE, + assertEquals("Should have correct cost", TestUtils.TEST_COST_VALUE, result[0].getField("cost")); } @@ -129,12 +124,12 @@ public void testGetSummaryProductCategoriesWithSingleCategory() throws Exception @Test public void testGetSummaryProductCategoriesWithMultipleEntriesSameCategory() throws Exception { ReportValuationStockData data1 = new ReportValuationStockData(); - setFieldValue(data1, CATEGORY_NAME, TEST_CATEGORY); - setFieldValue(data1, TOTAL_COST, TEST_COST_VALUE); + setFieldValue(data1, TestUtils.CATEGORY_NAME, TestUtils.TEST_CATEGORY); + setFieldValue(data1, TestUtils.TOTAL_COST, TestUtils.TEST_COST_VALUE); ReportValuationStockData data2 = new ReportValuationStockData(); - setFieldValue(data2, CATEGORY_NAME, TEST_CATEGORY); - setFieldValue(data2, TOTAL_COST, "50.00"); + setFieldValue(data2, TestUtils.CATEGORY_NAME, TestUtils.TEST_CATEGORY); + setFieldValue(data2, TestUtils.TOTAL_COST, "50.00"); ReportValuationStockData[] data = new ReportValuationStockData[] { data1, data2 }; @@ -143,9 +138,9 @@ public void testGetSummaryProductCategoriesWithMultipleEntriesSameCategory() thr (Object) data ); - assertNotNull(ERROR_RESULT_NULL, result); - assertEquals(ERROR_ONE_CATEGORY, 1, result.length); - assertEquals("Category name should match", TEST_CATEGORY, + assertNotNull(TestUtils.ERROR_RESULT_NULL, result); + assertEquals(TestUtils.ERROR_ONE_CATEGORY, 1, result.length); + assertEquals("Category name should match", TestUtils.TEST_CATEGORY, result[0].getField("category")); assertEquals("Total cost should be summed correctly", "150.00", result[0].getField("cost")); @@ -163,8 +158,8 @@ public void testGetSummaryProductCategoriesWithMultipleEntriesSameCategory() thr @Test public void testGetSummaryProductCategoriesWithNullCosts() throws Exception { ReportValuationStockData nullCostData = new ReportValuationStockData(); - setFieldValue(nullCostData, CATEGORY_NAME, TEST_CATEGORY); - setFieldValue(nullCostData, TOTAL_COST, null); + setFieldValue(nullCostData, TestUtils.CATEGORY_NAME, TestUtils.TEST_CATEGORY); + setFieldValue(nullCostData, TestUtils.TOTAL_COST, null); ReportValuationStockData[] data = new ReportValuationStockData[] { nullCostData }; @@ -173,8 +168,8 @@ public void testGetSummaryProductCategoriesWithNullCosts() throws Exception { (Object) data ); - assertNotNull(ERROR_RESULT_NULL, result); - assertEquals(ERROR_ONE_CATEGORY, 1, result.length); + assertNotNull(TestUtils.ERROR_RESULT_NULL, result); + assertEquals(TestUtils.ERROR_ONE_CATEGORY, 1, result.length); assertEquals("Cost should be zero for null values", "0", result[0].getField("cost")); } diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java index d4ce4f53c..4aa2ba4ec 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockWarehousesTest.java @@ -37,11 +37,6 @@ @RunWith(MockitoJUnitRunner.class) public class ReportValuationStockWarehousesTest { - private static final String CLIENT_ID = "testClient"; - private static final String ORG_ID = "testOrg"; - private static final String WAREHOUSE_ID_1 = "warehouse1"; - private static final String WAREHOUSE_ID_2 = "warehouse2"; - @InjectMocks private ReportValuationStock reportValuationStock; @@ -85,22 +80,22 @@ public void setUp() throws Exception { @Test public void testGetWarehousesWithResults() throws Exception { List expectedOrgIds = Arrays.asList("org1", "org2"); - List expectedWarehouseIds = Arrays.asList(WAREHOUSE_ID_1, WAREHOUSE_ID_2); + List expectedWarehouseIds = Arrays.asList(TestUtils.WAREHOUSE_ID_1, TestUtils.WAREHOUSE_ID_2); try (MockedStatic obContextMock = mockStatic(OBContext.class); MockedStatic obDalMock = mockStatic(OBDal.class)) { obContextMock.when(OBContext::getOBContext).thenReturn(mockOBContext); - when(mockOBContext.getOrganizationStructureProvider(CLIENT_ID)) + when(mockOBContext.getOrganizationStructureProvider(TestUtils.CLIENT_ID)) .thenReturn(mockOsp); - when(mockOsp.getNaturalTree(ORG_ID)) + when(mockOsp.getNaturalTree(TestUtils.ORG_ID)) .thenReturn(Set.copyOf(expectedOrgIds)); obDalMock.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); when(mockOBDal.getSession()).thenReturn(mockSession); when(mockSession.createQuery(anyString(), eq(String.class))) .thenReturn(mockQuery); - when(mockQuery.setParameterList((String) eq("orgIds"), (Collection) any())) + when(mockQuery.setParameterList((String) eq(TestUtils.ORG_IDS), (Collection) any())) .thenReturn(mockQuery); when(mockQuery.setParameter(eq("clientId"), any())) .thenReturn(mockQuery); @@ -110,8 +105,8 @@ public void testGetWarehousesWithResults() throws Exception { @SuppressWarnings("unchecked") List result = (List) getWarehousesMethod.invoke( reportValuationStock, - CLIENT_ID, - ORG_ID + TestUtils.CLIENT_ID, + TestUtils.ORG_ID ); assertEquals("Should return correct number of warehouses", @@ -135,16 +130,16 @@ public void testGetWarehousesWithNoResults() throws Exception { MockedStatic obDalMock = mockStatic(OBDal.class)) { obContextMock.when(OBContext::getOBContext).thenReturn(mockOBContext); - when(mockOBContext.getOrganizationStructureProvider(CLIENT_ID)) + when(mockOBContext.getOrganizationStructureProvider(TestUtils.CLIENT_ID)) .thenReturn(mockOsp); - when(mockOsp.getNaturalTree(ORG_ID)) + when(mockOsp.getNaturalTree(TestUtils.ORG_ID)) .thenReturn(Set.copyOf(expectedOrgIds)); obDalMock.when(OBDal::getReadOnlyInstance).thenReturn(mockOBDal); when(mockOBDal.getSession()).thenReturn(mockSession); when(mockSession.createQuery(anyString(), eq(String.class))) .thenReturn(mockQuery); - when(mockQuery.setParameterList((String) eq("orgIds"), (Collection) any())) + when(mockQuery.setParameterList((String) eq(TestUtils.ORG_IDS), (Collection) any())) .thenReturn(mockQuery); when(mockQuery.setParameter(eq("clientId"), any())) .thenReturn(mockQuery); @@ -154,8 +149,8 @@ public void testGetWarehousesWithNoResults() throws Exception { @SuppressWarnings("unchecked") List result = (List) getWarehousesMethod.invoke( reportValuationStock, - CLIENT_ID, - ORG_ID + TestUtils.CLIENT_ID, + TestUtils.ORG_ID ); assertTrue("Should return empty list when no warehouses found", diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/TestUtils.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/TestUtils.java new file mode 100644 index 000000000..10dac7c30 --- /dev/null +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/TestUtils.java @@ -0,0 +1,65 @@ +package com.etendoerp.reportvaluationstock.handler; + +/** + * Utility class for testing constants and utility methods related to stock valuation reports. + * + *

This class provides constant values for testing purposes, including identifiers, messages, + * formats, and other test-specific configurations. It is designed to be a utility class and + * should not be instantiated. + */ +public class TestUtils { + + /** + * Private constructor to prevent instantiation of the utility class. + * + * @throws IllegalStateException if an attempt to instantiate is made. + */ + private TestUtils() { + throw new IllegalStateException("Utility class"); + } + + public static final String TEST_DATE = "2024-01-01"; + public static final String TEST_ORG_ID = "testOrgId"; + public static final String TEST_WAREHOUSE_ID = "testWarehouseId"; + public static final String TEST_CATEGORY_ID = "testCategoryId"; + public static final String TEST_CURRENCY_ID = "testCurrencyId"; + public static final String TEST_CLIENT_ID = "testClientId"; + public static final String WAREHOUSE_NOT_IN_LE = "WarehouseNotInLE"; + + public static final String CLIENT_ID = "testClient"; + public static final String ORG_ID = "testOrg"; + public static final String WAREHOUSE_ID_1 = "warehouse1"; + public static final String WAREHOUSE_ID_2 = "warehouse2"; + + public static final String ERROR_RESULT_NULL = "Result should not be null"; + public static final String CATEGORY_NAME = "categoryName"; + public static final String TEST_CATEGORY = "TestCategory"; + public static final String TOTAL_COST = "totalCost"; + public static final String TEST_COST_VALUE = "100.00"; + public static final String ERROR_ONE_CATEGORY = "Should contain one category"; + + public static final String TEST_COST_TYPE = "AVA"; + public static final String TEST_ALGORITHM_NAME = "Average Algorithm"; + public static final String TEST_TRANSLATED_HEADER = "Translated Cost Header"; + public static final String TEST_TRANSLATED_VALUATION = "Translated Valuation Header"; + public static final String NUMBER_FORMAT = "#,##0.00"; + public static final String ERROR_PARAMETERS_NULL = "Parameters should not be null"; + public static final String NUMBER_FORMAT_KEY = "NUMBERFORMAT"; + public static final String ERROR_DECIMAL_FORMAT = "Should have correct decimal format"; + public static final String COST_FORMAT_KEY = "COSTFORMAT"; + + public static final String PROCESS_TIME = "processTime"; + + public static final String TEST_CURRENCY = "102"; + public static final String TEST_WAREHOUSE = "TEST_WAREHOUSE"; + public static final String TEST_ORG = "TEST_ORG"; + public static final String TEST_CLIENT = "TEST_CLIENT"; + public static final String TEST_LANGUAGE = "en_US"; + + public static final String DATE_NEXT = "dateNext"; + public static final String MAX_AGG_DATE = "maxAggDate"; + public static final String DATE_FORMAT = "dateFormat"; + public static final String ORG_IDS = "orgIds"; + public static final String ERROR_DATA_LENGTH = "Should return expected data length"; + public static final String ERROR_EXPECTED_DATA = "Should return expected data"; +} diff --git a/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java b/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java index 9942ac8b0..2e1172031 100644 --- a/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java +++ b/src-test/src/com/smf/jobs/defaults/CloneOrderHookTest.java @@ -168,8 +168,8 @@ public void testCloneOrder() throws Exception { assertNotNull("Cloned order should not be null", result); - verify(clonedOrder).setDocumentAction("CO"); - verify(clonedOrder).setDocumentStatus("DR"); + verify(clonedOrder).setDocumentAction(Utility.COMPLETE); + verify(clonedOrder).setDocumentStatus(Utility.DRAFT_STATUS); verify(clonedOrder).setPosted("N"); verify(clonedOrder).setProcessed(false); verify(clonedOrder).setDelivered(false); diff --git a/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java b/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java index a1da78a86..37072fe5e 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessInvoicesTest.java @@ -53,9 +53,6 @@ @RunWith(MockitoJUnitRunner.class) public class ProcessInvoicesTest { - public static final String SUCCESS = "Success"; - public static final String SHOULD_RETURN_SUCCESS_TYPE = "Should return success type"; - @Spy @InjectMocks @@ -123,7 +120,7 @@ public void testProcessInvoiceWithoutVoidDates() throws Exception { String invoiceId = "test-invoice-id"; String docAction = "CO"; OBError expectedResult = new OBError(); - expectedResult.setType(SUCCESS); + expectedResult.setType(Utility.SUCCESS); expectedResult.setMessage("Invoice processed successfully"); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { @@ -148,7 +145,7 @@ public void testProcessInvoiceWithoutVoidDates() throws Exception { null ); - assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Utility.SUCCESS, result.getType()); assertEquals("Should return correct message", "Invoice processed successfully", result.getMessage()); } } @@ -168,7 +165,7 @@ public void testProcessInvoiceWithVoidDates() throws Exception { String voidAcctDate = "2024-01-15"; OBError expectedResult = new OBError(); - expectedResult.setType(SUCCESS); + expectedResult.setType(Utility.SUCCESS); SimpleDateFormat jsonDateFormat = JsonUtils.createDateFormat(); Date testDate = jsonDateFormat.parse(voidDate); @@ -196,7 +193,7 @@ public void testProcessInvoiceWithVoidDates() throws Exception { voidAcctDate ); - assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Utility.SUCCESS, result.getType()); } } @@ -234,7 +231,7 @@ public void testActionWithSuccessfulProcessing() throws Exception { List mockInvoices = List.of(mockInvoice); OBError successResult = new OBError(); - successResult.setType(SUCCESS); + successResult.setType(Utility.SUCCESS); // Instead of using doReturn().when(), use reflection when(getInputContentsMethod.invoke(processInvoices, Invoice.class)) @@ -257,7 +254,7 @@ public void testActionWithSuccessfulProcessing() throws Exception { ActionResult result = processInvoices.action(parameters, isStopped); - assertEquals(SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); } } @@ -276,7 +273,7 @@ public void testPreRunWithLockedInvoice() throws Exception { List mockInvoices = List.of(mockInvoice); OBError successResult = new OBError(); - successResult.setType(SUCCESS); + successResult.setType(Utility.SUCCESS); try (MockedStatic obDalMock = mockStatic(OBDal.class); MockedStatic requestContextMock = mockStatic(RequestContext.class)) { diff --git a/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java b/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java index 46c198c64..59c75cbd2 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessOrdersDefaultsTest.java @@ -36,9 +36,6 @@ @RunWith(MockitoJUnitRunner.class) public class ProcessOrdersDefaultsTest { - public static final String RESULT_SHOULD_NOT_BE_NULL = "Result should not be null"; - public static final String ACTIONS = "actions"; - @InjectMocks private ProcessOrdersDefaults processOrdersDefaults; @@ -71,13 +68,13 @@ public void setUp() { public void testExecuteWithSingleDocumentStatus() throws Exception { Map parameters = new HashMap<>(); String content = new JSONObject() - .put("documentStatuses", new JSONArray().put("DR")) + .put("documentStatuses", new JSONArray().put(Utility.DRAFT_STATUS)) .put("isProcessing", "N") .put("tabId", "123") .toString(); FieldProvider mockFieldProvider = mock(FieldProvider.class); - when(mockFieldProvider.getField("ID")).thenReturn("CO"); + when(mockFieldProvider.getField("ID")).thenReturn(Utility.COMPLETE); FieldProvider[] mockFields = new FieldProvider[]{mockFieldProvider}; try (MockedStatic requestContextMock = mockStatic(RequestContext.class); @@ -91,7 +88,7 @@ public void testExecuteWithSingleDocumentStatus() throws Exception { any(), anyString(), eq(ProcessOrdersDefaults.ORDER_DOCUMENT_ACTION_REFERENCE_ID), - eq("DR"), + eq(Utility.DRAFT_STATUS), eq("N"), eq(ProcessOrdersDefaults.AD_TABLE_ID), eq("123") @@ -99,11 +96,11 @@ public void testExecuteWithSingleDocumentStatus() throws Exception { JSONObject result = processOrdersDefaults.execute(parameters, content); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); - assertTrue("Result should contain actions", result.has(ACTIONS)); - JSONArray actions = result.getJSONArray(ACTIONS); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); + assertTrue("Result should contain actions", result.has(Utility.ACTIONS)); + JSONArray actions = result.getJSONArray(Utility.ACTIONS); assertEquals("Should have one action", 1, actions.length()); - assertEquals("Should have correct action", "CO", actions.getString(0)); + assertEquals("Should have correct action", Utility.COMPLETE, actions.getString(0)); } } @@ -117,14 +114,14 @@ public void testExecuteWithSingleDocumentStatus() throws Exception { public void testExecuteWithMultipleDocumentStatuses() throws Exception { Map parameters = new HashMap<>(); String content = new JSONObject() - .put("documentStatuses", new JSONArray().put("DR").put("CO")) + .put("documentStatuses", new JSONArray().put(Utility.DRAFT_STATUS).put(Utility.COMPLETE)) .put("isProcessing", "N") .put("tabId", "123") .toString(); FieldProvider mockFieldProvider1 = mock(FieldProvider.class); FieldProvider mockFieldProvider2 = mock(FieldProvider.class); - when(mockFieldProvider1.getField("ID")).thenReturn("CO"); + when(mockFieldProvider1.getField("ID")).thenReturn(Utility.COMPLETE); when(mockFieldProvider2.getField("ID")).thenReturn("CL"); FieldProvider[] mockFields1 = new FieldProvider[]{mockFieldProvider1}; @@ -141,7 +138,7 @@ public void testExecuteWithMultipleDocumentStatuses() throws Exception { any(), anyString(), eq(ProcessOrdersDefaults.ORDER_DOCUMENT_ACTION_REFERENCE_ID), - eq("DR"), + eq(Utility.DRAFT_STATUS), eq("N"), eq(ProcessOrdersDefaults.AD_TABLE_ID), eq("123") @@ -152,7 +149,7 @@ public void testExecuteWithMultipleDocumentStatuses() throws Exception { any(), anyString(), eq(ProcessOrdersDefaults.ORDER_DOCUMENT_ACTION_REFERENCE_ID), - eq("CO"), + eq(Utility.COMPLETE), eq("N"), eq(ProcessOrdersDefaults.AD_TABLE_ID), eq("123") @@ -160,11 +157,11 @@ public void testExecuteWithMultipleDocumentStatuses() throws Exception { JSONObject result = processOrdersDefaults.execute(parameters, content); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); - assertTrue("Result should contain actions", result.has(ACTIONS)); - JSONArray actions = result.getJSONArray(ACTIONS); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); + assertTrue("Result should contain actions", result.has(Utility.ACTIONS)); + JSONArray actions = result.getJSONArray(Utility.ACTIONS); assertEquals("Should have two actions", 2, actions.length()); - assertEquals("First action should be CO", "CO", actions.getString(0)); + assertEquals("First action should be CO", Utility.COMPLETE, actions.getString(0)); assertEquals("Second action should be CL", "CL", actions.getString(1)); } } @@ -176,7 +173,7 @@ public void testExecuteWithMultipleDocumentStatuses() throws Exception { @Test public void testGetDocumentActionList() { FieldProvider mockFieldProvider = mock(FieldProvider.class); - when(mockFieldProvider.getField("ID")).thenReturn("CO"); + when(mockFieldProvider.getField("ID")).thenReturn(Utility.COMPLETE); FieldProvider[] mockFields = new FieldProvider[]{mockFieldProvider}; try (MockedStatic actionButtonUtilityMock = mockStatic(ActionButtonUtility.class)) { @@ -192,16 +189,16 @@ public void testGetDocumentActionList() { )).thenReturn(mockFields); List result = ProcessOrdersDefaults.getDocumentActionList( - "DR", + Utility.DRAFT_STATUS, "N", "123", mockVars, mockConnectionProvider ); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); assertEquals("Should have one action", 1, result.size()); - assertEquals("Should have correct action", "CO", result.get(0)); + assertEquals("Should have correct action", Utility.COMPLETE, result.get(0)); } } } \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java b/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java index 53f9ca5de..ccd43706d 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java @@ -34,7 +34,7 @@ @RunWith(MockitoJUnitRunner.class) public class ProcessOrdersTest { - public static final String SUCCESS = "Success"; + @Spy @InjectMocks @@ -83,9 +83,9 @@ public void setUp() throws Exception { @Test public void testProcessOrder() throws Exception { String orderId = "test-order-id"; - String docAction = "CO"; + String docAction = Utility.COMPLETE; OBError expectedResult = new OBError(); - expectedResult.setType(SUCCESS); + expectedResult.setType(Utility.SUCCESS); expectedResult.setMessage("Order processed successfully"); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { @@ -106,7 +106,7 @@ public void testProcessOrder() throws Exception { docAction ); - assertEquals("Should return success type", SUCCESS, result.getType()); + assertEquals("Should return success type", Utility.SUCCESS, result.getType()); assertEquals( "Should return correct message", "Order processed successfully", diff --git a/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java b/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java index 249708a99..e9fc86403 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessShipmentTest.java @@ -53,15 +53,6 @@ @RunWith(MockitoJUnitRunner.Silent.class) public class ProcessShipmentTest { - public static final String SUCCESS = "Success"; - public static final String TEST_MESSAGE = "Test message"; - public static final String SHIPMENT_PROCESSED_SUCCESSFULLY = "Shipment processed successfully"; - public static final String RESULT_SHOULD_NOT_BE_NULL = "Result should not be null"; - public static final String SHOULD_RETURN_SUCCESS_TYPE = "Should return success type"; - public static final String DOC_ACTION = "DocAction"; - - - /** * A testable subclass of {@code ProcessShipment} that exposes methods for testing. */ @@ -125,9 +116,9 @@ public void setUp() throws Exception { try (MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { messageMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn(TEST_MESSAGE); + .thenReturn(Utility.TEST_MESSAGE); messageMock.when(() -> OBMessageUtils.parseTranslation(anyString(), any())) - .thenReturn(TEST_MESSAGE); + .thenReturn(Utility.TEST_MESSAGE); } } @@ -140,10 +131,10 @@ public void setUp() throws Exception { @Test public void testProcessShipmentPrivateMethod() throws Exception { String shipmentId = "test-shipment-id"; - String docAction = "CO"; + String docAction = Utility.COMPLETE; OBError expectedResult = new OBError(); - expectedResult.setType(SUCCESS); - expectedResult.setMessage(SHIPMENT_PROCESSED_SUCCESSFULLY); + expectedResult.setType(Utility.SUCCESS); + expectedResult.setMessage(Utility.SHIPMENT_PROCESSED_SUCCESSFULLY); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); @@ -163,11 +154,11 @@ public void testProcessShipmentPrivateMethod() throws Exception { docAction ); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); - assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Utility.SUCCESS, result.getType()); assertEquals( "Should return correct message", - SHIPMENT_PROCESSED_SUCCESSFULLY, + Utility.SHIPMENT_PROCESSED_SUCCESSFULLY, result.getMessage() ); } @@ -181,13 +172,13 @@ public void testProcessShipmentPrivateMethod() throws Exception { @Test public void testActionWithSuccessfulProcessing() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put(DOC_ACTION, "CO"); + parameters.put(Utility.DOC_ACTION, Utility.COMPLETE); MutableBoolean isStopped = new MutableBoolean(false); List mockShipments = List.of(mockShipment); OBError successResult = new OBError(); - successResult.setType(SUCCESS); - successResult.setMessage(SHIPMENT_PROCESSED_SUCCESSFULLY); + successResult.setType(Utility.SUCCESS); + successResult.setMessage(Utility.SHIPMENT_PROCESSED_SUCCESSFULLY); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); @@ -208,8 +199,8 @@ public void testActionWithSuccessfulProcessing() throws Exception { ActionResult result = processShipment.action(parameters, isStopped); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); - assertEquals(SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); verify(mockProcessShipmentUtil, times(1)).process( anyString(), anyString(), @@ -247,7 +238,7 @@ public void testActionWithError() throws Exception { @Test public void testActionWithEmptyInput() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put(DOC_ACTION, "CO"); + parameters.put(Utility.DOC_ACTION, Utility.COMPLETE); MutableBoolean isStopped = new MutableBoolean(false); List emptyShipments = Collections.emptyList(); @@ -258,7 +249,7 @@ public void testActionWithEmptyInput() throws Exception { ActionResult result = processShipment.action(parameters, isStopped); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); assertEquals("Should return success type for empty input", Result.Type.SUCCESS, result.getType()); } @@ -272,10 +263,10 @@ public void testActionWithEmptyInput() throws Exception { @Test public void testProcessShipment() throws Exception { String shipmentId = "test-shipment-id"; - String docAction = "CO"; + String docAction = Utility.COMPLETE; OBError expectedResult = new OBError(); - expectedResult.setType(SUCCESS); - expectedResult.setMessage(SHIPMENT_PROCESSED_SUCCESSFULLY); + expectedResult.setType(Utility.SUCCESS); + expectedResult.setMessage(Utility.SHIPMENT_PROCESSED_SUCCESSFULLY); try (MockedStatic requestContextMock = mockStatic(RequestContext.class)) { requestContextMock.when(RequestContext::get).thenReturn(mockRequestContext); @@ -295,8 +286,8 @@ public void testProcessShipment() throws Exception { docAction ); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); - assertEquals(SHOULD_RETURN_SUCCESS_TYPE, SUCCESS, result.getType()); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Utility.SUCCESS, result.getType()); } } @@ -312,7 +303,7 @@ public void testProcessShipmentWithNullShipment() throws Exception { when(mockRequestContext.getVariablesSecureApp()).thenReturn(mockVars); try { - processShipmentMethod.invoke(processShipment, null, "CO"); + processShipmentMethod.invoke(processShipment, null, Utility.COMPLETE); fail("Should throw NullPointerException"); } catch (InvocationTargetException e) { assertTrue(e.getCause() instanceof NullPointerException); @@ -328,7 +319,7 @@ public void testProcessShipmentWithNullShipment() throws Exception { @Test public void testActionWithInvalidDocAction() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put(DOC_ACTION, "INVALID_ACTION"); + parameters.put(Utility.DOC_ACTION, "INVALID_ACTION"); MutableBoolean isStopped = new MutableBoolean(false); List mockShipments = List.of(mockShipment); @@ -351,7 +342,7 @@ public void testActionWithInvalidDocAction() throws Exception { )).thenReturn(errorResult); messageMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn(TEST_MESSAGE); + .thenReturn(Utility.TEST_MESSAGE); // Replace doReturn with reflection-based mocking when(getInputContentsMethod.invoke(processShipment, ShipmentInOut.class)) @@ -372,7 +363,7 @@ public void testActionWithInvalidDocAction() throws Exception { @Test public void testActionWithMultipleShipments() throws Exception { JSONObject parameters = new JSONObject(); - parameters.put(DOC_ACTION, "CO"); + parameters.put(Utility.DOC_ACTION, Utility.COMPLETE); MutableBoolean isStopped = new MutableBoolean(false); ShipmentInOut mockShipment2 = mock(ShipmentInOut.class); @@ -380,7 +371,7 @@ public void testActionWithMultipleShipments() throws Exception { List multipleShipments = Arrays.asList(mockShipment, mockShipment2, mockShipment3); OBError successResult = new OBError(); - successResult.setType(SUCCESS); + successResult.setType(Utility.SUCCESS); try (MockedStatic requestContextMock = mockStatic(RequestContext.class); MockedStatic messageMock = mockStatic(OBMessageUtils.class)) { @@ -401,7 +392,7 @@ public void testActionWithMultipleShipments() throws Exception { )).thenReturn(successResult); messageMock.when(() -> OBMessageUtils.messageBD(anyString())) - .thenReturn(TEST_MESSAGE); + .thenReturn(Utility.TEST_MESSAGE); // Replace doReturn with reflection-based mocking when(getInputContentsMethod.invoke(processShipment, ShipmentInOut.class)) @@ -410,8 +401,8 @@ public void testActionWithMultipleShipments() throws Exception { ActionResult result = processShipment.action(parameters, isStopped); - assertNotNull(RESULT_SHOULD_NOT_BE_NULL, result); - assertEquals(SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); verify(mockProcessShipmentUtil, times(3)).process( anyString(), anyString(), diff --git a/src-test/src/com/smf/jobs/defaults/Utility.java b/src-test/src/com/smf/jobs/defaults/Utility.java new file mode 100644 index 000000000..66dff12bc --- /dev/null +++ b/src-test/src/com/smf/jobs/defaults/Utility.java @@ -0,0 +1,39 @@ +package com.smf.jobs.defaults; + +/** + * Utility class that provides constant values and prevents instantiation. + * + *

This class contains constants used across various parts of the application, such as + * status codes, messages, and SQL queries. It is designed to be a utility class and should + * not be instantiated. + */ +public class Utility { + + /** + * Private constructor to prevent instantiation of the utility class. + * + * @throws IllegalStateException if an attempt to instantiate is made. + */ + private Utility() { + throw new IllegalStateException("Utility class"); + } + + public static final String SUCCESS = "Success"; + public static final String TEST_MESSAGE = "Test message"; + public static final String SHIPMENT_PROCESSED_SUCCESSFULLY = "Shipment processed successfully"; + public static final String RESULT_SHOULD_NOT_BE_NULL = "Result should not be null"; + public static final String SHOULD_RETURN_SUCCESS_TYPE = "Should return success type"; + public static final String DOC_ACTION = "DocAction"; + + public static final String TEST_ID = "testId" ; + + static final String DRAFT_STATUS = "DR"; + + public static final String COMPLETE = "CO"; + public static final String ACTIONS = "actions"; + + public static final String QUERY_ORDERS_WITHOUT_TAX = "SELECT * FROM Orders WHERE includeTax = 'N'"; + public static final String LINES_INCLUDE_TAXES = "linesIncludeTaxes"; + public static final String TRUE = "true"; + +} \ No newline at end of file diff --git a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java index 082770682..54cf0b68a 100644 --- a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java +++ b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrderTest.java @@ -15,6 +15,7 @@ import com.smf.jobs.ActionResult; import com.smf.jobs.Result; +import com.smf.jobs.defaults.Utility; /** * Unit tests for the {@link CreateFromOrder} class. @@ -60,8 +61,8 @@ public void testActionWithRefreshButton() throws Exception { ActionResult result = createFromOrder.action(parameters, isStopped); - assertNotNull("Result should not be null", result); - assertEquals("Should return success type", Result.Type.SUCCESS, result.getType()); + assertNotNull(Utility.RESULT_SHOULD_NOT_BE_NULL, result); + assertEquals(Utility.SHOULD_RETURN_SUCCESS_TYPE, Result.Type.SUCCESS, result.getType()); } /** diff --git a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java index f8f62ebd2..cf0d54784 100644 --- a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java +++ b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java @@ -11,6 +11,8 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import com.smf.jobs.defaults.Utility; + /** * Unit test class for {@link CreateFromOrdersHQLTransformer}. * This class contains test cases to verify the behavior of the HQL query transformer @@ -28,11 +30,6 @@ @ExtendWith(MockitoExtension.class) public class CreateFromOrdersHQLTransformerTest { - public static final String QUERY_ORDERS_WITHOUT_TAX = "SELECT * FROM Orders WHERE includeTax = 'N'"; - public static final String LINES_INCLUDE_TAXES = "linesIncludeTaxes"; - public static final String TRUE = "true"; - - private CreateFromOrdersHQLTransformer transformer; private String baseHqlQuery; @@ -55,7 +52,7 @@ void setUp() { @Test void testTransformHqlQueryWhenLinesIncludeTaxesIsTrue() { Map requestParameters = new HashMap<>(); - requestParameters.put(LINES_INCLUDE_TAXES, TRUE); + requestParameters.put(Utility.LINES_INCLUDE_TAXES, Utility.TRUE); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); @@ -71,12 +68,12 @@ void testTransformHqlQueryWhenLinesIncludeTaxesIsTrue() { @Test void testTransformHqlQueryWhenLinesIncludeTaxesIsFalse() { Map requestParameters = new HashMap<>(); - requestParameters.put(LINES_INCLUDE_TAXES, "false"); + requestParameters.put(Utility.LINES_INCLUDE_TAXES, "false"); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - Assertions.assertEquals(QUERY_ORDERS_WITHOUT_TAX, result); + Assertions.assertEquals(Utility.QUERY_ORDERS_WITHOUT_TAX, result); } /** @@ -91,7 +88,7 @@ void testTransformHqlQueryWhenLinesIncludeTaxesParameterIsMissing() { String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - Assertions.assertEquals(QUERY_ORDERS_WITHOUT_TAX, result); + Assertions.assertEquals(Utility.QUERY_ORDERS_WITHOUT_TAX, result); } /** @@ -104,7 +101,7 @@ void testTransformHqlQueryWithMultipleReplacements() { String queryWithMultipleReplacements = "SELECT * FROM Orders WHERE includeTax = @linesIncludeTaxes@ AND otherField = @linesIncludeTaxes@"; Map requestParameters = new HashMap<>(); - requestParameters.put(LINES_INCLUDE_TAXES, TRUE); + requestParameters.put(Utility.LINES_INCLUDE_TAXES, Utility.TRUE); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(queryWithMultipleReplacements, requestParameters, queryNamedParameters); @@ -120,12 +117,12 @@ void testTransformHqlQueryWithMultipleReplacements() { @Test void testTransformHqlQueryWithInvalidBooleanValue() { Map requestParameters = new HashMap<>(); - requestParameters.put(LINES_INCLUDE_TAXES, "invalid_boolean"); + requestParameters.put(Utility.LINES_INCLUDE_TAXES, "invalid_boolean"); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - Assertions.assertEquals(QUERY_ORDERS_WITHOUT_TAX, result); + Assertions.assertEquals(Utility.QUERY_ORDERS_WITHOUT_TAX, result); } /** @@ -135,7 +132,7 @@ void testTransformHqlQueryWithInvalidBooleanValue() { @Test void testTransformHqlQueryWithEmptyQuery() { Map requestParameters = new HashMap<>(); - requestParameters.put(LINES_INCLUDE_TAXES, TRUE); + requestParameters.put(Utility.LINES_INCLUDE_TAXES, Utility.TRUE); Map queryNamedParameters = new HashMap<>(); String result = transformer.transformHqlQuery("", requestParameters, queryNamedParameters); @@ -151,7 +148,7 @@ void testTransformHqlQueryWithEmptyQuery() { @Test void testTransformHqlQueryWithNullQuery() { Map requestParameters = new HashMap<>(); - requestParameters.put(LINES_INCLUDE_TAXES, TRUE); + requestParameters.put(Utility.LINES_INCLUDE_TAXES, Utility.TRUE); Map queryNamedParameters = new HashMap<>(); assertThrows(NullPointerException.class, () -> diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java index f149acaa6..c86f54ecb 100644 --- a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddOrgTest.java @@ -28,6 +28,8 @@ import org.openbravo.model.pricing.priceadjustment.PriceAdjustment; import org.hibernate.Session; +import com.smf.jobs.defaults.Utility; + /** * Test class for the {@link OfferAddOrg} functionality. * This class contains unit tests to verify the behavior of the OfferAddOrg class, @@ -45,8 +47,6 @@ @ExtendWith(MockitoExtension.class) public class OfferAddOrgTest { - private static final String TEST_ID = "testId" ; - @Mock private OBDal obDal; @@ -97,10 +97,10 @@ public void testDoPickAndExecuteSingleOrganization() throws JSONException { JSONArray selectedLines = new JSONArray(); JSONObject orgJson = new JSONObject(); - orgJson.put("id", TEST_ID); + orgJson.put("id", Utility.TEST_ID); selectedLines.put(orgJson); - when(obDal.getProxy(eq(Organization.ENTITY_NAME), eq(TEST_ID))).thenReturn(organization); + when(obDal.getProxy(eq(Organization.ENTITY_NAME), eq(Utility.TEST_ID))).thenReturn(organization); OBProvider obProvider = mock(OBProvider.class); OrganizationFilter mockOrgFilter = mock(OrganizationFilter.class); @@ -141,7 +141,7 @@ public void testDoPickAndExecuteMultipleOrganizations() throws JSONException { JSONArray selectedLines = new JSONArray(); for (int i = 0; i < 150; i++) { JSONObject orgJson = new JSONObject(); - orgJson.put("id", TEST_ID + i); + orgJson.put("id", Utility.TEST_ID + i); selectedLines.put(orgJson); } diff --git a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java index ce0245b31..0ba5983f4 100644 --- a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductCategoryTest.java @@ -26,6 +26,8 @@ import org.openbravo.model.pricing.priceadjustment.PriceAdjustment; import org.hibernate.Session; +import com.smf.jobs.defaults.Utility; + /** * Unit tests for the {@link OfferAddProductCategory} class. * @@ -36,8 +38,6 @@ @ExtendWith(MockitoExtension.class) public class OfferAddProductCategoryTest { - private static final String TEST_ID = "testId" ; - @Mock private OBDal obDal; @@ -87,11 +87,11 @@ public void testDoPickAndExecuteSingleProductCategory() throws JSONException { JSONArray selectedLines = new JSONArray(); JSONObject productCatJson = new JSONObject(); - productCatJson.put("id", TEST_ID); + productCatJson.put("id", Utility.TEST_ID); selectedLines.put(productCatJson); ProductCategory productCategory = mock(ProductCategory.class); - when(obDal.getProxy(eq(ProductCategory.ENTITY_NAME), eq(TEST_ID))).thenReturn(productCategory); + when(obDal.getProxy(eq(ProductCategory.ENTITY_NAME), eq(Utility.TEST_ID))).thenReturn(productCategory); OBProvider obProvider = mock(OBProvider.class); org.openbravo.model.pricing.priceadjustment.ProductCategory mockProductCategory = @@ -131,7 +131,7 @@ public void testDoPickAndExecuteMultipleProductCategories() throws JSONException JSONArray selectedLines = new JSONArray(); for (int i = 0; i < 150; i++) { JSONObject productCatJson = new JSONObject(); - productCatJson.put("id", TEST_ID + i); + productCatJson.put("id", Utility.TEST_ID + i); selectedLines.put(productCatJson); }