Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore several void method calls inside a void method in Mockito

Tags:

I'm testing a void method that happens to call several other void methods in a class (all of these methods are in the same class). The method is something along these lines...

public void methodToTest() {    methodA();    methodB(); }  void methodA() {    methodA1();    methodA2();    methodA3(); } 

What I'd like to do is cause methodA() above to do nothing. That is, I want methodA() to basically be like this:

void methodA() { } 

I've tried both doThrow() and doAnswer() on methodA() to no avail. It's as if those are both being completely ignored.

An example of what I've tried...

doThrow(new RuntimeException()).when(mockedClass).methodA(); 

Is there a way to do this just using Mockito? I'm not at liberty to change the class that's being modified.

like image 675
Zack Macomber Avatar asked Oct 31 '12 18:10

Zack Macomber


People also ask

Can Mockito throw exceptions on void methods?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

How do you skip a method in JUnit?

The JUnit 4 @Ignore annotation could be applied for a test method, to skip its execution. In this case, you need to use @Ignore with the @Test annotation for a test method you wish to skip. The annotation could also be applied to the test class, to skip all the test cases under a class.

How do you unit test a void method without arguments?

Your modified program can ask for user input, call the function, then print the output. A testing framework can supply the input from a list of inputs to test, and check the outputs against the expected values. To test as-is, you'd have to intercept the input and output streams.


1 Answers

If you are looking to have methodB still execute, while methodA does nothing. This will do that:

TestClass spy = spy(new TestClass()); doNothing().when(spy).methodA(); spy.methodToTest();  
like image 121
Chris D Avatar answered Nov 17 '22 00:11

Chris D