Apex Unit Testing: test data and Test.setMock

Posted by in apex, salesforce

Recently, I was QAing some Apex unit tests and I kept encountering the notorious Apex System.CalloutException: “You have uncommitted work pending. Please commit or rollback before calling out” while running a unit test that created some test data before performing a callout (that was properly mocked via Test.setMock). After some debugging, I realized the test only failed when I inserted the test data via my TestFactory class; when I created the test data directly inside the test method, the test passed. I think this must be an issue with the Apex unit testing framework, so I’m posting this here in the hopes it may save a developer hours (or days) of frustration. Has anyone run into this before?