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,320 points
34,198 views

10 answers to this question.

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,620 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
4 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,450 points

edited Nov 7, 2018 by Omkar 79,310 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,120 points
2,060 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,910 points
2,836 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,910 points
4,144 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,120 points
3,758 views
0 votes
2 answers

How do I replace character from string at specific indexes?

You could turn the String into a ...READ MORE

answered Aug 22, 2019 in Java by Sirajul
• 59,230 points
22,290 views
0 votes
2 answers

When to use Static Methods in Java?

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

answered Aug 10, 2018 in Java by samarth295
• 2,220 points
15,529 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,620 points
893 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,910 points
16,655 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP