模拟isAssignableFrom()

时间:2018-07-12 06:02:37

标签: java mockito

我有两个如下的Java类,

public class Class1{
    private Object actionObject;    
    public Object getActionObject() {
        return actionObject;
    }
    public void setActionObject(Object actionObject) {
        this.actionObject = actionObject;
    }
}

第二堂课

 public class Class2 {
    private Long id;
    private int idver;  
    private int valueDate;
}

有以下两种说法,

Class1 deserializedValue = (Class1) event.getDeserializedValue();

Class2.class.isAssignableFrom(deserializedValue.getActionObject().getClass());

我想模仿第二条语句

Class2.class.isAssignableFrom(deserializedValue.getActionObject().getClass());

我该怎么做?

1 个答案:

答案 0 :(得分:1)

出于测试目的,您可以使用策略模式。您只需要具有两个不同实现的接口或抽象类。其中之一是模拟实现,如下所示:

public interface EventStrategy {

    // More methods...

    boolean isAssignableFrom(final Object object);

}

public class MyEvent implements EventStrategy {

    public boolean isAssignableFrom(final Object object) {
        return Class2.class.isAssignableFrom(object.getClass());
    }

}

public class MockEvent implements EventStrategy {

    public boolean isAssignableFrom(final Object object) {
        return true;
    }

}