Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

java - 如何使用Mockito模拟void方法(How to mock void methods with Mockito)

How to mock methods with void return type?

(如何用void返回类型模拟方法?)

I implemented an observer pattern but I can't mock it with Mockito because I don't know how.

(我实现了一个观察者模式,但是我不能用Mockito模拟它,因为我不知道怎么做。)

And I tried to find an example on the Internet but didn't succeed.

(我试图在互联网上找到一个例子,但没有成功。)

My class looks like this:

(我的课看起来像这样:)

public class World {

    List<Listener> listeners;

    void addListener(Listener item) {
        listeners.add(item);
    }

    void doAction(Action goal,Object obj) {
        setState("i received");
        goal.doAction(obj);
        setState("i finished");
    }

    private string state;
    //setter getter state
} 

public class WorldTest implements Listener {

    @Test public void word{
    World  w= mock(World.class);
    w.addListener(this);
    ...
    ...

    }
}

interface Listener {
    void doAction();
}

The system is not triggered with mock.

(系统不会通过模拟触发。)

I want to show the above-mentioned system state.

(我想显示上述系统状态。)

And make assertions according to them.

(并根据他们做出断言。)

  ask by ibrahimyilmaz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Take a look at the Mockito API docs .

(看一下Mockito API文档 。)

As the linked document mentions (Point # 12) you can use any of the doThrow() , doAnswer() , doNothing() , doReturn() family of methods from Mockito framework to mock void methods.

(正如链接文档中提到的那样(第12点),您可以使用doThrow()中的doThrow()doAnswer()doNothing()doReturn()系列方法中的任何一种来模拟void方法。)

For example,

(例如,)

Mockito.doThrow(new Exception()).when(instance).methodName();

or if you want to combine it with follow-up behavior,

(或者如果您想将其与后续行为结合起来,)

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState .

(假设您正在模拟以下类World中的setter setState(String s) ,则代码使用doAnswer方法来模拟setState 。)

World  mockWorld = mock(World.class); 
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      System.out.println("called with arguments: " + Arrays.toString(args));
      return null;
    }
}).when(mockWorld).setState(anyString());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...