23

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. Each test passes when run alone.
  2. The first test always passes - this is true if I switch the order of the tests in the file.

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.

Thanks, Anne

4

4 に答える 4

18

私はまだ細心の注意を払っていませんが、これは疑わしいようです:

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

anyObject()マッチャーであり、リプレイ後に呼び出しています。オブジェクトの生成には使用されません。EasyMock に任意のオブジェクトを許可するように指示するために使用されます。EasyMock は余分なマッチャーを検出していますが、2 回目のテストまでは害はありません。その時点で、EasyMock が記録したがまだ使用していないマッチャーの数 (2) は、2 番目のdoXthing呼び出しで予想されるパラメーターの数 (1) と一致しません。

(または再生モードのモック)に実際のパラメーターを渡す必要があります。直接、または のような実際の値testCallingXthingを渡してみてください。null2

于 2011-07-01T15:48:38.450 に答える
2

試す:

String testResult = mainThing.testCallingXthing(eq(EasyMock.anyLong()));

より洗練されたマッチャーがありanyObject()ます。これらを使用すると、共同作業者に関する型ベースのアサーションを作成できます。

EasyMockのドキュメントから:

eq(X value)
実際の値が期待値と等しい場合に一致します。すべてのプリミティブ タイプとオブジェクトで使用できます。
anyBoolean(), anyByte(), anyChar(), anyDouble(), anyFloat(), anyInt(), anyLong(), anyObject()_anyShort()

于 2011-07-01T15:54:23.473 に答える