2

メソッドのパラメーターに副作用を引き起こすクラスのメソッドがあります。

public void SideEffectsClass {
    public void doSomethingWithSideEffects(List<Object> list) {
        // do something to the list
    }
}

そして、このクラスがテストされています:

public void ClassUnderTest() {
   public List<Object> execute() {
       List<Object> results = new ArrayList<Object>();
       new SideEffectsClass().doSomethingWithSideEffects(results);
       return results;
   }
}

JMockit を使用した私のテスト方法:

@Test
public void test() throws Exception
{
    // arrange
    new Expectations()
    {
        SideEffectsClass sideEffects;
        {
            new SideEffectsClass();
            sideEffects.doSomethingWithSideEffects((List<Object>) any);
            // I want to simulate that the List<Object> parameter has changed 
            // (has more elements, less elements, etc. after this method is called
        }
    };

    // act
    ClassUnderTest testClass = new ClassUnderTest();
    List<Object> results = testClass.execute();

    // assert
    Assert.assertEquals(myExpectedResults, results);
}
4

2 に答える 2

4

Delegateオブジェクトを使用して引数の値を変更できます。

    sideEffects.doSomethingWithSideEffects((List<Object>) any);
    result = new Delegate() {
        void delegate(List<Object> list) { list.add(new Object()); }
    };

メソッドが呼び出されたことを確認するだけであればdoSomethingWithSideEffects、テストは次のように簡単に記述できます。

@Test
public void test(final SideEffectsClass sideEffects)
{
    List<Object> results = new ClassUnderTest().execute();

    assertEquals(myExpectedResults, results);

    new Verifications() {{
        sideEffects.doSomethingWithSideEffects((List<Object>) any);
    }};
}
于 2011-07-31T22:26:54.273 に答える
0

As the test is trying to tell you, the side effects aren't part of the behavior of ClassUnderTest. Don't try to test that here. Based on the code you're showing, all you should be testing is that results is passed to doSomethingWithSideEffects() and that the same object is returned from execute(). Being unfamiliar with JMockit syntax, I can't tell you exactly how to write it.

Aside: I do recommend, however, that everyone using a tool like jMock, JMockit, or EasyMock should use Mockito instead if they can.

于 2011-07-31T20:00:52.360 に答える