【问题标题】:Easymock.expect throws IllegalStateExceptionEasymock.expect 抛出 IllegalStateException
【发布时间】:2020-04-13 07:57:44
【问题描述】:

我在这段代码中看到了,

expect(myService.getAll(anyBoolean())).andReturn(objectList).anyTimes();
replay(scopeService);

那个期望语句正在抛出 IllegalStateException - missing behavior definition for the preceding method call: myService.getAll(true) Usage is: expect(a.foo()).andXXX()

我知道如果我没有 andReturn,或者如果我错过了调用重播,或者我的对象不是模拟对象,它会引发此异常。我已经检查了所有这些,但事实并非如此!有人可以让我知道是否还有其他问题吗? 我之前有大约 50 次预期/重播,没有任何问题。

【问题讨论】:

    标签: java unit-testing easymock


    【解决方案1】:

    您没有提供更多代码,所以我假设您的代码或多或少是这样的:

    import static org.easymock.EasyMock.*;
    
    public class SomeTests {
        static class Foo {
            public List<Integer> getAll(boolean value) {
                throw new RuntimeException();
            }
        }
    
        public void someTestCase() {
            Foo mock = createMock(Foo.class);
            List<Integer> ret = Collections.singletonList(1);
            expect(mock.getAll(anyBoolean())).andStubReturn(ret);
            replay(mock);
    
            mock.getAll(true); // returns a list with single element 1 rather than throwing an exception
        }
    }
    

    我的建议是:

    1. 检查myService 实例是否由其中一种模拟方法创建
    2. 应该在 myService 上调用回复,因为它会切换模拟模式

    【讨论】:

      【解决方案2】:

      我发现了这个问题。问题是模拟 myService 被用于创建正在测试的对象(因为它具有它作为成员)并创建测试所需的另一个模拟对象。 当我将它们更改为使用两个不同的 myService(myService, myService1) 时,它起作用了!我不确定这会有什么帮助,但确实有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-10
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-17
        相关资源
        最近更新 更多