本文介绍了EasyMock:java.lang.IllegalStateException:预期有1个匹配器,已记录2个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用EasyMock 2.5.2和JUnit 4.8.2(通过Eclipse运行)时遇到问题。我在这里阅读了所有类似的帖子,但没有找到答案。我有一个包含两个测试相同方法的测试的类。我正在使用匹配器。

I am having a problem with EasyMock 2.5.2 and JUnit 4.8.2 (running through Eclipse). I have read all the similar posts here but have not found an answer. I have a class containing two tests which test the same method. I am using matchers.


  1. 单独运行时每个测试都会通过。

  2. 第一个测试始终会通过-如果我切换文件中测试的顺序,则为true。

这是测试代码的简化版本:

Here is a simplified version of the test code:

private Xthing mockXthing;
private MainThing mainThing;

@Before
public void setUp() {
    mockXthing = EasyMock.createMock(Xthing.class);
    mainThing = new MainThing();
    mainThing.setxThing(mockXthing);
}

@After
public void cleanUp() {
    EasyMock.reset(mockXthing);
}

@Test
public void testTwo() {
    String abc = "abc";
    EasyMock.expect(mockXthing.doXthing((String) EasyMock.anyObject())).andReturn(abc);
    EasyMock.replay(mockXthing);
    String testResult = mainThing.testCallingXthing((Long) EasyMock.anyObject());
    assertEquals("abc", testResult);
    EasyMock.verify(mockXthing);
}

@Test
public void testOne() {
    String xyz = "xyz";
    EasyMock.expect(mockXthing.doXthing((String) EasyMock.anyObject())).andReturn(xyz);
    EasyMock.replay(mockXthing);
    String testResult = mainThing.testCallingXthing((Long) EasyMock.anyObject());
    assertEquals("xyz", testResult);
    EasyMock.verify(mockXthing);
}

第二次(或最后一次)测试始终失败,并出现以下错误:

The second (or last) test always fails with the following error:

java.lang.IllegalStateException: 1 matchers expected, 2 recorded

任何对此的见识将不胜感激。

Any insight to this would be greatly appreciated.

谢谢,
安妮

推荐答案

我还没有仔细观察,但这看起来很可疑:

I haven't looked meticulously closely yet, but this looks suspect:

String testResult = mainThing.testCallingXthing((Long) EasyMock.anyObject());

anyObject()是一个匹配器,您在重播后将其称为。它不用于生产任何物体。它用于指示EasyMock allow 任何对象。 EasyMock正在检测该额外的匹配器,但是直到第二次测试它才是有害的。那时,EasyMock已记录但尚未使用的匹配器数量(2)与第二个 doXthing 调用的预期参数数量不符(1)。

anyObject() is a matcher and you're calling it after the replay. It's not used to produce any object. It's used to instruct EasyMock to allow any object. EasyMock is detecting that extra matcher but it is not harmful until the second test. At that point, the number of matchers that EasyMock has recorded but hasn't yet used (2) doesn't line up with the number of parameters expected for the second doXthing call (1).

您应该将 real 参数传递给 testCallingXthing (或处于重播模式的模拟)。尝试直接传递 null 或真实值(例如 2 )。

You should be passing in real parameters to testCallingXthing (or a mock that is in replay mode). Try passing in null directly, or a real value like 2.

这篇关于EasyMock:java.lang.IllegalStateException:预期有1个匹配器,已记录2个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:58