5

我似乎无法弄清楚如何使用 Mockito 模拟一个简单的 setter 方法。我有以下课程:

class MyClass {
    private SomeObject someObject;

    public void setSomeObject(SomeObject someObject) {
        this.someObject = someObject;
    }

    public someObject getSomeObject() {
        return someObject;
    }
}

现在我只想在调用“setSomeObject”时设置一个新的“SomeObject”实例。设置器中的参数也应该被忽略。

我需要这样的东西:

MyClass mockedClass = mock(MyClass.class);
when(mockedClass.setSomeObject([ignoreWhatsInHere]))
    .then(mockedClass.setSomeObject(new SomeObject();

但是,我似乎无法让语法为此工作。我只能使用 getters() 让模拟程序工作,因为这样我就可以返回一些东西。但我不知道如何为 setters() 做同样的事情。

所有帮助表示赞赏。

4

1 回答 1

5

You should be able to use the doThrow()|doAnswer()|doNothing()|doReturn() family of methods to perform a suitable action when testing methods that return void including setters. So instead of

when(mockedObject.someMethod()).thenReturn(something)

you would use doAnswer() to return a custom Answer object, although it's not terribly elegant, and you might be better off using a stub:

doAnswer(new Answer() { 
    public Object answer(InvocationOnMock invocation) {
          //whatever code you want to run when the method is called
          return null;
  }}).when(mockedObject).someMethod();
}

If you are trying to return different values from the same getter call, you may also want to look at mockito's consecutive stubbing calls, which will allow you to, for example, throw an error for the first call of a method, and then return an object from the second call.

see http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#12 for more details on both of these.

于 2013-04-18T09:59:06.980 回答