derirative23
derirative23

Reputation: 496

How to mock method in java/groovy?

I got two methods:

protected List<CustomObject> getSortedOrderItems() {
    List<CustomObject> internalList = new ArrayList<>();
    //some operations
    return internalList;
}

public CustomObject getIdentifire() {
    CustomObject correctIdentifire = null;
    List<CustomObject> items = getSortedOrderItems();
    //some opearations on items
    return correctIdentifire;
}

For my Junit tests I need to mock List<CustomObject> items = getSortedItems(); as a list of my customObjects

I dont know how to start it. I am aware how to use Mockito in normal cases but never done something like this. Any help?

Upvotes: 0

Views: 3108

Answers (2)

injecteer
injecteer

Reputation: 20709

In groovy you can simply use meta-programming to mock anything directly:

class SomeClass {
  protected List<CustomObject> getSortedOrderItems() {
    List<CustomObject> internalList = new ArrayList<>();
    //some operations
    return internalList;
  }
}

@groovy.transform.TupleConstructor
class CustomObject { int a }

// test setup:
SomeClass.metaClass.getSortedOrderItems = {-> [ new CustomObject(1), new CustomObject(2) ] }

// test
assert [ 1, 2 ] == new SomeClass().sortedOrderItems*.a

Upvotes: 3

uminder
uminder

Reputation: 26170

I understand that you want to mock a certain method and leave other methods of a given class untouched. For such cases, you can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Assuming that the mentioned methods are part of the class named MyClass, you could

// given
MyClass myClass = new MyClass();
MyClass spy = spy(myClass );
List<CustomObject> myCustomObjects = Arrays.asList(new CustomObject(1), new CustomObject(1), ...);
when(spy.getSortedOrderItems()).thenReturn(myCustomObjects);

// when 
CustomObject result = spy.getIdentifire();

// then
CustomObject expected = myCustomObjects.get(0); // whatever object you expect
assertEquals(expected , resultXml); 

Upvotes: 1

Related Questions