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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With