如何使用EasyMock为新关键字编写期望语句?

我只想使用EasyMock为行 filter = new Simple(A.ATTRIBUTE_actIVE,Operator.EQUALS,Boolean.TRUE); 编写Expect语句。

//SingleLimit.java
private Limitation filter;

protected final Limitation getBaseLimitation() {
    Validate.notNull(type);
    GroupClass Group = new GroupClass(GroupTypeclass.SELECTOR);
    if (activatable.class.isAssignableFrom(typelisted)) {
        if (A.class.isAssignableFrom(type)) {
        //expect statement for below line
        filter = new Simple(A.ATTRIBUTE_actIVE,Operator.EQUALS,Boolean.TRUE); 
        }
     }
    }


   //Simple.java
   public class Simple implements Serializable,Limitation
   {
     public Simple(String path,Operator operator,Object value) {
    this(path,operator,new Object[]{value});
   }
    }

任何帮助将不胜感激

dutacmdownload 回答:如何使用EasyMock为新关键字编写期望语句?

我将创建一个创建简单对象的新类。

public class SimpleFactory {
    public Simple createSimple(....) {
        return new Simple(....);
    }
}

比将此工厂注入类或将其作为参数传递

public YourClazz(SimpleFactory simpleFactory) {

    //constructor 
    this.simpleFactory = simpleFactory;

    protected final Limitation getBaseLimitation() {
        ///...
        //filter = new Simple(A.ATTRIBUTE_ACTIVE,Operator.EQUALS,Boolean.TRUE);
        //change this to
        filter = simpleFactory.createSimple(A.ATTRIBUTE_ACTIVE,Boolean.TRUE);
    }

    //or pass as parameter
    protected final Limitation getBaseLimitation(SimpleFactory simpleFacotry) {
        ///...
        //filter = new Simple(A.ATTRIBUTE_ACTIVE,Boolean.TRUE);
    }    
}

现在,在您的测试代码中创建一个simpleFactory的模拟。

///编辑2019/11/16另一种解决方案

如果无法创建其他类,请在您的类中创建新方法,然后将其用于创建新的Simple对象:

    public YourClazz {

        protected Simple createSimple(....) {
            return new Simple(....);
        }

        protected final Limitation getBaseLimitation() {
            //...
            //filter = new Simple(A.ATTRIBUTE_ACTIVE,Boolean.TRUE);
            //change this to
            filter = createSimple(A.ATTRIBUTE_ACTIVE,Boolean.TRUE);
    //...
        }    
}

现在可以进行测试了,您可以创建类的部分模拟并模拟createSimple方法:

YourClazz mock = partialMockBuilder(YourClazz.class)
      .addMockedMethod("createSimple").createMock();


Simple expectedSimple = new Simple(....);      

expect(mock.createSimple(.....).andReturn(expectedSimple);
replay(mock);
本文链接:https://www.f2er.com/3096778.html

大家都在问