How to make mock to void methods with mockito

+1 vote

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

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

My class looks like

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 are not triggered with mock. =( I want to show above mentioned system state. And make assertion according to them.

Jun 21, 2018 in Java by developer_1
• 3,220 points
5,369 views

10 answers to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

ake a look at the Mockito API docs. 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.

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  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());
answered Jun 21, 2018 by Rishabh
• 3,520 points
0 votes

Try this:

Mockito.doCallRealMethod().when(<objectInstance>).<method>();
<objectInstance>.<method>();
answered Dec 7, 2018 by rajneesh
0 votes
<Object> <objectInstance> = mock(<Object>.class, Mockito.CALLS_REAL_METHODS);

This is the best way to use mock to your mockito. It worked fine for me. Hope this helps.

answered Dec 7, 2018 by Trisha
0 votes
Read this article for better understanding of mockito

https://static.javadoc.io/org.mockito/mockito-core/2.23.4/org/mockito/Mockito.html
answered Dec 7, 2018 by Aniket
0 votes
import static org.mockito.Mockito.*;

mockito offers "Spy" for using partial mock function.

You can use it as follows:

private World world = spy(World.class);

To eliminate a method from being executed you could use something like this:

doNothing().when(someObject).someMethod(anyObject());

to give some custom behaviour to a method use "when" with an "thenReturn":

doReturn("something").when(this.world).someMethod(anyObject());
answered Dec 7, 2018 by Vishal Kumar
0 votes
answered Dec 7, 2018 by Taki
0 votes
answered Dec 7, 2018 by reslovebug
0 votes
public class Test {
    @Mock
    private test1 t1;
    @InjectMocks
    private Test service;
    @Before
    public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
    }
    @Test
    public void trythis() {
         //assertion here
    }
}

This way you can use mock using mockito

answered Dec 7, 2018 by Nabarupa
0 votes
This article can give the idea on what is mock and how to use it using mockito

https://www.journaldev.com/21834/mockito-mock-void-method
answered Dec 7, 2018 by Abhinav
0 votes

You can use partial mocking to serve the purpose also

Mockito’s doCallRealMethod() can be used for void methods.

answered Dec 7, 2018 by nitesh

Related Questions In Java

+5 votes
3 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,360 points

edited Nov 6, 2018 by Omkar 4,646 views
0 votes
1 answer

How to pad an integer with zeros on the left in Java?

Use java.lang.String.format() method. String.format("%05d", number) ...READ MORE

answered May 31, 2018 in Java by Daisy
• 8,020 points
47 views
0 votes
2 answers

How to left pad a string with zero in java?

String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0") the second ...READ MORE

answered Aug 31, 2018 in Java by Sushmita
• 6,820 points
151 views
0 votes
1 answer
0 votes
2 answers

“Could not find or load main class” mean?

Use the final modifier to enforce good initialization. Avoid returning ...READ MORE

answered Sep 18, 2018 in Java by Sushmita
• 6,820 points
1,221 views
0 votes
2 answers

What is the use of toString method in Java and how can I use it ?

Whenever you require to explore the constructor ...READ MORE

answered Aug 23, 2018 in Java by Daisy
• 8,020 points
158 views
0 votes
1 answer

How do I replace character from string at specific indexes?

String are immutable in Java. You can't ...READ MORE

answered Apr 26, 2018 in Java by Rishabh
• 3,520 points
25 views
0 votes
2 answers

When to use Static Methods in Java?

A static method has two main purposes: For ...READ MORE

answered Aug 9, 2018 in Java by samarth295
• 2,190 points
58 views
0 votes
1 answer

How to divide a string in two parts

String s="yourstring"; boolean flag = true; for(int i=0;i<s.length();i++) { ...READ MORE

answered Apr 13, 2018 in Java by Rishabh
• 3,520 points
32 views
0 votes
2 answers

How do I read and convert an InputStream object to string type?

You can also use Java Standard Library ...READ MORE

answered Jul 17, 2018 in Java by Sushmita
• 6,820 points
1,558 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.