Skip to content

Add ability to mock method called with specific argument value.  #20

@justin-lyon

Description

@justin-lyon

This is quite a nice feature in Mockito, which has a similar grammar to to UniversalMocker (not sure if that was intentional or not)

But essentially allowing me to return different values (or throw different exceptions) by both method Name AND the argument values passed into the method.

This feature is required in order to test some recursive logic I've got that recursively calls a Custom Metadata's Parent until it has crawled to the top of the parent child hierarchy.

https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#stubbing
image

Sample method that this feature would be great for testing with

// How a Sample Test might Look
mdtServiceStub.when('getInstance')
  .with('GrandParent')
  .thenReturn(new Config__mdt(DeveloperName = 'GrandParent')); 
mdtServiceStub.when('getInstance')
  .with('Parent')
  .thenReturn(new Config__mdt(DeveloperName = 'Parent', ParentName__c = 'GrandParent'));
mdtServiceStub.when('getInstance')
  .with('Child')
  .thenReturn(new Config__mdt(DeveloperName = 'Child', ParentName__c = 'Parent'));

Caller sut = new Caller();
List<Config__mdt> configs = sut.crawlConfig('Child');

// ...Assert that the List<Config__mdt> has all three items after recursively calling getInstance with different mdt Names
// Sample Unit
public List<Config__mdt> crawlConfig(final String name) {
  List<Config__mdt> configMdts = new List<Config__mdt>();
  Config__mdt mdt = mdtService.getInstance(name);

  if (String.isNotBlank(mdt.ParentName__c)) {
    // Crawl up the Parents
    List<Config__mdt> parents = crawlConfig(name);
    configMdts.addAll(parents);
  }

  // Add children last
  configMdts.add(mdt);

  return configMdts;
}

// --> End Result is a List sorted in hierarchical order, Parent to Child.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions