我不确定我在做什么错。我的代码中存在此错误,因此我写了一个简单的示例来尝试确定错误所在。

我有一个ClassA,它依赖于ServiceA和ServiceB两个服务,我正在尝试测试ClassA,并模拟ServiceA和ServiceB。

  /**
 * Last edited by: $Author: cg $
 * on: $Date: 17 Jun 2011 11:36:25 $
 * Filename: $RCSfile: ClassA.java,v $
 * Revision: $Revision:   $
 */
package easy;

import java.util.HashMap;


/**
 *
 * @version $Revision: $, $Date: 17 Jun 2011 11:36:25 $
 */
public class ClassA {
    private ServiceA serviceA;
    private ServiceB serviceB;
    public ClassA(ServiceA a, ServiceB b) {
        this.serviceA = a;
        this.serviceB = b;
    }
    public String process(String p) {
        HashMap<String,String> a = serviceA.getServiceA(p);
        String ret = serviceB.getServiceB(a);
        return ret;
    }
}


interface ServiceA{
    HashMap<String,String>getServiceA(String s);
}

interface ServiceB{
    String getServiceB(HashMap<String,String> p);
}


我的测试如下:

/**
 * Last edited by: $Author: cg $
 * on: $Date: 17 Jun 2011 11:43:05 $
 * Filename: $RCSfile: ClassATest.java,v $
 * Revision: $Revision:   $
 */
package easy;

import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;

import java.util.HashMap;

import junit.framework.Assert;

import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Test;
/**
 *
 * @version $Revision: $, $Date: 17 Jun 2011 11:43:05 $
 */
public class ClassATest {

    @Test
    public void testProcess() {
        IMocksControl mockery = EasyMock.createControl();
        mockery.resetToStrict();
        mockery.checkOrder(true);

        ServiceA serviceA = EasyMock.createMock("ServiceA",ServiceA.class);
        ServiceB serviceB = EasyMock.createMock("ServiceB",ServiceB.class);

        ClassA a = new ClassA(serviceA, serviceB);

        String myParam = "My Test";

        HashMap<String,String> retFromServiceA = new HashMap<String,String>();
        retFromServiceA.put("my", "name");
        expect(serviceA.getServiceA(eq(myParam))).andReturn(retFromServiceA);
        expect(serviceB.getServiceB(retFromServiceA)).andReturn(myParam);

        mockery.replay();
        String actual = a.process(myParam);
        mockery.verify();

        Assert.assertEquals(myParam, actual);
    }
}


结果失败,因为实际的回报为空。

我尝试调试代码,但我意识到尽管我期望我说我希望ServiceA.getServiceA返回retFromServiceA,但事实并非如此。它返回null。

有任何想法吗?

最佳答案

ServiceS和ServiceS是在不使用嘲笑控件的情况下创建的,因此应使用:

EasyMock.replay(serviceA, serviceB);

在执行处理方法之前

07-24 14:46