[SalesForce] Simulate DML error in Unit test

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

public class MyServiceLocator {

    private static final Map<Type, Type> customTypesMap = new Map<Type, Type> {
        MyIDatabase.class => MyDatabase.class,

        // Services
        MyICustomObjectService.class => MyCustomObjectService.class,
        MyIHttpService.class => MyHttpService.class,

        // DAOs
        MyICustomObjectDao.class => MyCustomObjectDao.class
    };

    private static final Map<Type, Type> testTypesMap = new Map<Type, Type> {
        // Mocks
        MyICustomObjectDao.class => MyTestCustomObjectDao.class,
        MyIHttpService.class = MyTestHttpService.class
    };

    public static Type resolve(Type t) {
        if (Test.isRunningTest()) {
            if (testTypesMap.containsKey(t)) {
                return testTypesMap.get(t);
            }
        }

        if (customTypesMap.containsKey(t)) {
            return customTypesMap.get(t);
        }

        return t;
    }

}

And in MyTestCustomObjectDao I can throw exceptions. For different behaviors you can add flag for unit test (throw or not throw exceptions).

Related Topic