+ Start a Discussion
Michael Johnson 29Michael Johnson 29 

Behavior: Unit Tests for Method in Managed Package using Mock.

We have run into an issue when running unit tests that call a class from a managed package using a mock. When doing data manipulation within a test method (inserting new records) calling the class returns null value (in the case below a string 'Success' is expected to return).

@isTest(SeeAllData=true)
	static void testMock1() {
		system.debug(ManagedPackage1.Class1.ReturnSuccess('result', new ManagedPackage1.MockGenerator.Result1());
	}


Running the test above, the debug of 'Success' returns as expected. However, if any data manipulation is done at the beginning of the test method, null is always returned.
 

@isTest(SeeAllData=true)
	static void testMock1() {
		Account a = new Account();
		insert a;
		system.debug(ManagedPackage1.Class1.ReturnSuccess('result', new ManagedPackage1.MockGenerator.Result1());
	}

The bahavior completely changes, and the debug returns null. We have found a way around it doing the following.

@isTest(SeeAllData=true)
	static void testMock1() {
		Account a = new Account();
		insert a;
		test.starttest();
		system.debug(ManagedPackage1.Class1.ReturnSuccess('result', new ManagedPackage1.MockGenerator.Result1());
		test.stoptest();
	}
The result returns 'Success' as intended wrapped in test.starttest() and test.stoptest(). If the insert of the Account is also done within the start and stop test, the debug is again null. Any ideas as to why this behaves the way it does?

 

cstarkcstark
I've run into the same issue. Adding the calls to startTest() and stopTest() cause the mock to perform properly, but are only required if DML is performed before running the code that utilizes the mock.

Any insights as to why?