develop an approach to Acumatica customization development that maximizes the unit-testability of custom code, and that still allows the same degree of extensibility that Acumatica provides by default using PXGraphExtensions and PXCacheExtensions
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// Business logic interface
public interface IOrderProcessingService
{
decimal CalculateDiscount(Order order, Customer customer);
bool ValidateOrder(Order order);
void ProcessOrder(Order order);
}
// Business logic implementation
public class OrderProcessingService : IOrderProcessingService
{
private readonly ICustomerRepository _customerRepository;
private readonly IInventoryRepository _inventoryRepository;
private readonly IEmailService _emailService;
public OrderProcessingService(
ICustomerRepository customerRepository,
IInventoryRepository inventoryRepository,
IEmailService emailService)
{
_customerRepository = customerRepository;
_inventoryRepository = inventoryRepository;
_emailService = emailService;
}
public decimal CalculateDiscount(Order order, Customer customer)
{
// Pure business logic - easily testable
if (customer.IsPreferred && order.Total > 1000)
return order.Total * 0.1m;
return 0;
}
public bool ValidateOrder(Order order)
{
return order.Lines.All(line => line.Quantity > 0) &&
order.CustomerID.HasValue;
}
public void ProcessOrder(Order order)
{
var customer = _customerRepository.GetCustomer(order.CustomerID.Value);
if (ValidateOrder(order))
{
var discount = CalculateDiscount(order, customer);
order.Discount = discount;
if (customer.Email != null)
_emailService.SendOrderConfirmation(customer.Email, order.OrderNbr);
}
}
}
2. Repository Layer Abstractions
csharp
public interface ICustomerRepository
{
Customer GetCustomer(int customerId);
IEnumerable<Customer> GetCustomersBySalesPerson(int salesPersonId);
}
public interface IInventoryRepository
{
InventoryItem GetItem(string inventoryId);
decimal GetAvailableQuantity(string inventoryId, int? warehouseId);
}
// Acumatica-specific implementation
public class AcumaticaCustomerRepository : ICustomerRepository
{
private readonly PXGraph _graph;
public AcumaticaCustomerRepository(PXGraph graph)
{
_graph = graph;
}
public Customer GetCustomer(int customerId)
{
var customer = PXSelect<Customer,
Where<Customer.bAccountID, Equal<Required<Customer.bAccountID>>>>
.Select(_graph, customerId);
return customer;
}
// Implementation...
}
3. Thin Graph Extensions
csharp
public class SOOrderEntryExt : PXGraphExtension<SOOrderEntry>
{
public IOrderProcessingService OrderProcessingService { get; set; }
public override void Initialize()
{
base.Initialize();
// Dependency injection - can be overridden in tests
OrderProcessingService = ServiceLocator.GetService<IOrderProcessingService>()
?? new OrderProcessingService(
new AcumaticaCustomerRepository(Base),
new AcumaticaInventoryRepository(Base),
new EmailService());
}
public PXAction<SOOrder> ProcessOrder;
[PXButton]
[PXUIField(DisplayName = "Process Order")]
protected virtual IEnumerable processOrder(PXAdapter adapter)
{
var order = Base.Document.Current;
if (order != null)
{
// Convert Acumatica entity to business entity
var businessOrder = MapToBusinessEntity(order);
// Execute business logic through service
OrderProcessingService.ProcessOrder(businessOrder);
// Map back to Acumatica entity
MapFromBusinessEntity(businessOrder, order);
}
return adapter.Get();
}
private Order MapToBusinessEntity(SOOrder soOrder)
{
// Mapping logic - keep simple
return new Order
{
OrderNbr = soOrder.OrderNbr,
CustomerID = soOrder.CustomerID,
Total = soOrder.OrderTotal ?? 0,
Lines = Base.Transactions.Select().Cast<SOLine>()
.Select(MapLineToBusinessEntity).ToList()
};
}
private SOLine MapFromBusinessEntity(Order businessOrder, SOOrder soOrder)
{
soOrder.OrderTotal = businessOrder.Total;
soOrder.CuryDiscAmt = businessOrder.Discount;
return soOrder;
}
}
4. Cache Extensions with Events
csharp
public class SOLineExt : PXCacheExtension<SOLine>
{
public static bool EventsEnabled = true;
[PXMergeAttributes(Method = MergeMethod.Merge)]
[PXUIField(DisplayName = "Custom Field")]
public string UsrCustomField { get; set; }
public class Events : PXEntityEventSubscriber<SOLine>
{
public override void RowInserted(PXCache cache, SOLine item, bool isDirty)
{
if (!EventsEnabled) return;
var service = ServiceLocator.GetService<ILineProcessingService>();
if (service != null)
{
service.ProcessNewLine(item);
}
}
}
}
Testing Strategy
1. Unit Tests for Business Logic
csharp
[TestFixture]
public class OrderProcessingServiceTests
{
private Mock<ICustomerRepository> _customerRepoMock;
private Mock<IInventoryRepository> _inventoryRepoMock;
private Mock<IEmailService> _emailServiceMock;
private OrderProcessingService _service;
[SetUp]
public void Setup()
{
_customerRepoMock = new Mock<ICustomerRepository>();
_inventoryRepoMock = new Mock<IInventoryRepository>();
_emailServiceMock = new Mock<IEmailService>();
_service = new OrderProcessingService(
_customerRepoMock.Object,
_inventoryRepoMock.Object,
_emailServiceMock.Object);
}
[Test]
public void CalculateDiscount_PreferredCustomerWithLargeOrder_Returns10Percent()
{
// Arrange
var order = new Order { Total = 1500 };
var customer = new Customer { IsPreferred = true };
// Act
var discount = _service.CalculateDiscount(order, customer);
// Assert
Assert.AreEqual(150, discount);
}
[Test]
public void ProcessOrder_ValidOrder_SendsEmail()
{
// Arrange
var order = new Order { CustomerID = 1, OrderNbr = "000001" };
var customer = new Customer { Email = "test@example.com" };
_customerRepoMock.Setup(x => x.GetCustomer(1)).Returns(customer);
// Act
_service.ProcessOrder(order);
// Assert
_emailServiceMock.Verify(x => x.SendOrderConfirmation(
"test@example.com", "000001"), Times.Once);
}
}
2. Integration Tests for Extensions
csharp
[TestFixture]
public class SOOrderEntryExtTests
{
private SOOrderEntry _graph;
private SOOrderEntryExt _extension;
private Mock<IOrderProcessingService> _serviceMock;
[SetUp]
public void Setup()
{
// Create graph in test mode
PXGraph.SuppressLongRunningAttribute = true;
_graph = PXGraph.CreateInstance<SOOrderEntry>();
// Get extension
_extension = _graph.GetExtension<SOOrderEntryExt>();
// Mock service
_serviceMock = new Mock<IOrderProcessingService>();
_extension.OrderProcessingService = _serviceMock.Object;
}
[Test]
public void ProcessOrder_Action_CallsService()
{
// Arrange
var order = new SOOrder { OrderNbr = "000001" };
_graph.Document.Insert(order);
// Act
_graph.Actions["ProcessOrder"].Press();
// Assert
_serviceMock.Verify(x => x.ProcessOrder(It.IsAny<Order>()), Times.Once);
}
}
Dependency Injection Setup
1. Service Locator Pattern
csharp
public static class ServiceLocator
{
private static readonly Dictionary<Type, object> _services =
new Dictionary<Type, object>();
public static void RegisterService<T>(T service)
{
_services[typeof(T)] = service;
}
public static T GetService<T>()
{
return _services.ContainsKey(typeof(T)) ? (T)_services[typeof(T)] : default(T);
}
public static void Clear()
{
_services.Clear();
}
}
2. Test Configuration
csharp
[TestFixture]
public class TestSetup
{
[OneTimeSetUp]
public void GlobalSetup()
{
// Register test services
ServiceLocator.RegisterService<IOrderProcessingService>(
new Mock<IOrderProcessingService>().Object);
ServiceLocator.RegisterService<ICustomerRepository>(
new Mock<ICustomerRepository>().Object);
}
[OneTimeTearDown]
public void GlobalTeardown()
{
ServiceLocator.Clear();
}
}
Benefits of This Approach
1. Maximum Testability
Business logic completely isolated from Acumatica framework
Easy mocking of dependencies
Fast unit tests without database access
2. Maintained Extensibility
Uses standard Acumatica extension patterns
Multiple extensions can still be applied
Event-based programming still works
3. Clean Separation
Framework concerns separated from business logic
Easier maintenance and refactoring
Better code organization
4. Flexibility
Services can be easily swapped for testing
Different implementations for different environments
Easy to add new functionality
Implementation Guidelines
Keep Graph Extensions Thin: Only framework glue code
Extract Business Logic: Move to service layer
Use Interfaces: For all dependencies
Mock External Systems: Email, file systems, APIs
Test at Multiple Levels: Unit, integration, and end-to-end
Use Constructor Injection: When possible, with fallbacks
Maintain Mapping Logic: Keep entity mapping simple and testable
This approach allows you to write highly testable customizations while fully leveraging Acumatica's powerful extension mechanisms.