I have a piece of code which upserts some objects. My code is robust enough to handle any DML failures. But i want to test it out in Unit tests.
Is there a way i can simulate DML failures?
General functioning of code –
//Create a Master Object1. Upsert it
//Create multiple Detail record under Object1, and upsert them
My code makes sure that if Master Object1 didn't get upserted (due to any DML failure), its handled well and it wont get to upserting Detail. Or if a single detail object record fails, everything gets rolled back and the exception is handled well. I want to test that functionality in unit test.
How can i do that? In manual test, i generally make a field required, then let the code run, and then revert the field back to not required. Can something like this be simulated in unit test?
Best Answer
My way in this situations - using Service Locator
And in MyTestCustomObjectDao I can throw exceptions. For different behaviors you can add flag for unit test (throw or not throw exceptions).