简体   繁体   English

如何在 java/groovy 中模拟方法?

[英]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();对于我的 Junit 测试,我需要模拟List<CustomObject> items = getSortedItems(); as a list of my customObjects作为我的 customObjects 列表

I dont know how to start it.我不知道如何开始。 I am aware how to use Mockito in normal cases but never done something like this.我知道如何在正常情况下使用 Mockito 但从未做过这样的事情。 Any help?有什么帮助吗?

In groovy you can simply use meta-programming to mock anything directly:在 groovy 中,您可以简单地使用元编程直接模拟任何东西:

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

I understand that you want to mock a certain method and leave other methods of a given class untouched.我知道您想模拟某个方法,而保留给定 class 的其他方法不变。 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).当您使用spy时,会调用真正的方法(除非方法被存根)。

Assuming that the mentioned methods are part of the class named MyClass , you could假设上述方法是名为MyClass的 class 的一部分,您可以

// 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM