diff --git a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockAddParametersTest.java index b471cd39..db393b0a 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 f386c6cc..7e19ef93 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 9945de1b..e47ff731 100644 --- a/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java +++ b/src-test/src/com/etendoerp/reportvaluationstock/handler/ReportValuationStockGetReportTest.java @@ -62,6 +62,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. @@ -106,12 +115,12 @@ public void testGetReportDataWithCostTypeAndNoWarehouseConsolidation() throws Ex 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" + 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]); } } @@ -136,12 +145,12 @@ public void testGetReportDataWithoutCostTypeAndWithWarehouseConsolidation() thro 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" + 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]); } } @@ -166,12 +175,12 @@ public void testGetReportDataWithoutCostTypeAndNoWarehouseConsolidation() throws 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" + 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 4309d190..abf17c1d 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 98a35f93..ac827718 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 de57d080..9942ac8b 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 16ae525d..00000000 --- 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 01cb3a7b..a1da78a8 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 1d115213..46c198c6 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 072e1cc2..f03e53e2 100644 --- a/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java +++ b/src-test/src/com/smf/jobs/defaults/ProcessOrdersTest.java @@ -27,9 +27,11 @@ import org.openbravo.base.weld.WeldUtils; import org.openbravo.client.kernel.RequestContext; import org.openbravo.erpCommon.utility.OBError; +import org.openbravo.model.common.invoice.Invoice; import org.openbravo.model.common.order.Order; import org.openbravo.service.db.DalConnectionProvider; +import com.smf.jobs.Action; import com.smf.jobs.ActionResult; import com.smf.jobs.Result; @@ -42,6 +44,8 @@ @RunWith(MockitoJUnitRunner.class) public class ProcessOrdersTest { + public static final String SUCCESS = "Success"; + @Spy @InjectMocks private ProcessOrders processOrders; @@ -62,6 +66,8 @@ public class ProcessOrdersTest { private Order mockOrder; private Method processOrderMethod; + private Method getInputContentsMethod; + /** * Sets up the test environment, initializing mock dependencies and @@ -77,6 +83,13 @@ public void setUp() throws Exception { String.class ); processOrderMethod.setAccessible(true); + + // Get the protected method from the Action superclass + getInputContentsMethod = Action.class.getDeclaredMethod( + "getInputContents", + Class.class + ); + getInputContentsMethod.setAccessible(true); } /** @@ -111,7 +124,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 +133,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 b5873119..9e0a3733 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(), @@ -205,13 +224,14 @@ public void testActionWithSuccessfulProcessing() throws Exception { * when an unexpected condition occurs during shipment processing. */ @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 +246,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 +273,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 +294,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 +327,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 +350,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 +371,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 +379,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 +400,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 +427,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 f7fdbc2d..08277068 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 421b055b..8591aef6 100644 --- a/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java +++ b/src-test/src/com/smf/jobs/defaults/invoices/CreateFromOrdersHQLTransformerTest.java @@ -1,27 +1,52 @@ 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 { 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<>(); @@ -30,9 +55,14 @@ void testTransformHqlQueryWhenLinesIncludeTaxesIsTrue() { 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<>(); @@ -41,9 +71,14 @@ void testTransformHqlQueryWhenLinesIncludeTaxesIsFalse() { String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + Assertions.assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", 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,9 +86,14 @@ void testTransformHqlQueryWhenLinesIncludeTaxesParameterIsMissing() { String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + Assertions.assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", 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 = @@ -64,9 +104,14 @@ void testTransformHqlQueryWithMultipleReplacements() { 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<>(); @@ -75,9 +120,13 @@ void testTransformHqlQueryWithInvalidBooleanValue() { String result = transformer.transformHqlQuery(baseHqlQuery, requestParameters, queryNamedParameters); - assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", result); + Assertions.assertEquals("SELECT * FROM Orders WHERE includeTax = 'N'", 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<>(); @@ -86,17 +135,22 @@ void testTransformHqlQueryWithEmptyQuery() { 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"); 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 49bb36b3..f149acaa 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 cae15838..ce0245b3 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 7e222f5e..e4f22ceb 100644 --- a/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java +++ b/src-test/src/com/smf/jobs/defaults/offerPick/OfferAddProductTest.java @@ -5,10 +5,12 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; +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 +119,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 65b67f45..a227b66f 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; } }