使用EasyMock模拟方法

huangapple go评论70阅读模式
英文:

mock methods with EasyMock

问题

我尝试为以下方法创建单元测试但我找不到在每个方法内部模拟调用的解决方案您能否通过使用EasyMock为这些方法创建JUnit测试来帮助我

private static final WebServiceCache<JWebService> SERVICE = new WebServiceCache<>();
public int getCount() {
    int res = -1;
    try {
        String count = SERVICE.invokeSecurelly(new WS<String>() {
            @Override
            public String execute() throws Exception {
                return getWS().getList();
            }
        });
        res = Integer.parseInt(count);
    } catch (Exception e) {
        LOGGER.error("Count Exception" + e);
    }
    return res;
}

public int getKeyNumber() {
    int res = -1;
    try {
        String keyId = SERVICE.invokeSecurelly(new WS<String>() {
            @Override
            public String execute() throws Exception {
                return getWS().getID();
            }
        });

        res = Integer.parseInt(keyId);
    } catch (Exception e) {
        LOGGER.error("getKeyNumBer returns an error" + e);
    }
    return res;
}

提前致谢
英文:

I try to create unit test fro the following method but i can't find a solution to mock the call inside each method, Could you please help me with creating Junit Test for those methods using EasyMock :

private static final WebServiceCache&lt;JWebService&gt; SERVICE = new WebServiceCache&lt;&gt;();
public int getCount() {
	int res = -1;
	try {
		String count = SERVICE.invokeSecurelly(new WS&lt;String&gt;() {
			@Override
			public String execute() throws Exception {
				return getWS().getList();
			}
		});
		res = Integer.parseInt(count);
	} catch (Exception e) {
		LOGGER.error(&quot;Count Exception&quot; + e);
	}
	return res;
}

public int getKeyNumber() {
	int res = -1;
	try {
		String keyId = SERVICE.invokeSecurelly(new WS&lt;String&gt;() {
			@Override
			public String execute() throws Exception {
				return getWS().getID();
			}
		});
		
		res = Integer.parseInt(keyId);
	} catch (Exception e) {
		LOGGER.error(&quot;getKeyNumBer returns an error&quot; + e);
	}
	return res;
}

Thanks in advance

答案1

得分: 1

要做一些干净的事情你需要进行一些重构使其可测试这是我最终会得到的内容... 猜测你示例中缺失的核心部分

public class MyClass {
    private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());
    private final WebServiceCache<JWebService> service;

    public MyClass(WebServiceCache<JWebService> service) {
        this.service = service;
    }

    private int getValue(Supplier<String> invoked) {
        try {
            String count = service.invokeSecurelly(invoked::get);
            return Integer.parseInt(count);
        } catch (Exception e) {
            LOGGER.error("Count Exception", e);
        }
        return -1;
    }

    public int getCount() {
        return getValue(() -> getWS().getList());
    }

    public int getKeyNumber() {
        return getValue(() -> getWS().getID());
    }

    private Stuff getWS() { // 猜测 getWS() 在哪
        return null;
    }
}

从这里开始,如果我们假设你想要模拟的是 getWS(),代码会是这样的。

import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.easymock.EasyMock.expect;

public class MyClassTest extends EasyMockSupport {

    private WebServiceCache<JWebService> cache = new WebServiceCache<>();
    private MyClass tested = partialMockBuilder(MyClass.class)
            .addMockedMethod("getWS")
            .withConstructor(cache)
            .mock();
    private Stuff stuff = mock(Stuff.class);

    @Before
    public void before() {
        expect(tested.getWS()).andStubReturn(stuff);
    }

    @Test
    public void getCount() {
        expect(stuff.getList()).andStubReturn("8");
        replayAll();

        assertThat(tested.getCount()).isEqualTo(8);
    }

    @Test
    public void getKeyNumber() {
        expect(stuff.getID()).andStubReturn("8");
        replayAll();

        assertThat(tested.getKeyNumber()).isEqualTo(8);
    }
}
英文:

To do something clean, you need some refactoring to make it testable. Here is what I would end up with... guessing part of the missing core in your example.

public class MyClass {
    private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());
    private final WebServiceCache&lt;JWebService&gt; service;

    public MyClass(WebServiceCache&lt;JWebService&gt; service) {
        this.service = service;
    }
    
    private int getValue(Supplier&lt;String&gt; invoked) {
        try {
            String count = service.invokeSecurelly(invoked::get);
            return Integer.parseInt(count);
        } catch (Exception e) {
            LOGGER.error(&quot;Count Exception&quot;, e);
        }
        return -1;
    }

    public int getCount() {
        return getValue(() -&gt; getWS().getList());
    }

    public int getKeyNumber() {
        return getValue(() -&gt; getWS().getID());
    }

    private Stuff getWS() { // guessing where getWS() is
        return null;
    }
}

From there, if we assume it's getWS() that you want to mock, it would look like this.

import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.easymock.EasyMock.expect;

public class MyClassTest extends EasyMockSupport {

    private WebServiceCache&lt;JWebService&gt; cache = new WebServiceCache&lt;&gt;();
    private MyClass tested = partialMockBuilder(MyClass.class)
            .addMockedMethod(&quot;getWS&quot;)
            .withConstructor(cache)
            .mock();
    private Stuff stuff = mock(Stuff.class);

    @Before
    public void before() {
        expect(tested.getWS()).andStubReturn(stuff);
    }

    @Test
    public void getCount() {
        expect(stuff.getList()).andStubReturn(&quot;8&quot;);
        replayAll();

        assertThat(tested.getCount()).isEqualTo(8);
    }

    @Test
    public void getKeyNumber() {
        expect(stuff.getID()).andStubReturn(&quot;8&quot;);
        replayAll();

        assertThat(tested.getKeyNumber()).isEqualTo(8);
    }
}

huangapple
  • 本文由 发表于 2020年9月15日 22:57:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63904555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定