Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement custom implementation behavior configuration #79

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

scolladon
Copy link
Contributor

@scolladon scolladon commented Dec 16, 2024

Description

Allow the end developer to create a class to specify complex behavior
Useful when need to mutate the arguments
like Answer in Mockito but inspired by jest API

Motivation and Context

Allow developers to specify special behavior when mocking Database.insert()
This kind of call add an Id fields to each SObject records.
It is currently not possible to do that with the current apex-mockery implementation.
This PR aims to allow this.

Ex :

public interface DB {
  void insertRecords(List<SObject> sobjects);
}

public class MyService {
	DB aDB;
	public MyService(DB aDB) {
		this.aDB = aDB;
	}

	public void insertAccount(Account acc) {
		this.aDB.insertRecords(new List<Account>{acc});
	}
}

@isTest
private class MyServiceTest {

	class InsertMock implements MethodSpy.ConfiguredBehavior {
		public Object apply(final List<Object> params) { // Mutate the params
			for(SObject sob : (List<SObject>) params[0]) {
				sob.Id = generateFakeId(Account.SObjectType);
			}
		}
	}
	
	@isTest
	static void insertAccount_generateId() {
		// Arrange
		Mock dbMock = Mock.forType(DB.class);
		MethodSpy insertSpy = dbMock.spyOn('insertRecords');
		MyService sut = new MyService((DB) dbMock.stub);
		Account acc = new Account();
		insertSpy.mockImplementation(new InsertMock());

		// Act
		sut.insertAccount(acc);

		// Assert
		Assert.isNotNull(acc.Id);
	}
}

How Has This Been Tested?

Dedicated unit tests
New recipes

@scolladon
Copy link
Contributor Author

Opening the debate around the names that will be exposed after this PR is merged

For the newly exposed ConfiguredBehavior interface :

  • SpyBehavior 👈
  • MethodAction
  • CallHandler

For its apply method :

  • handleCall 👈
  • execute
  • invoke

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant