And my client class (you could say it looks like this): I'm creating unit tests for SomeClient#getEntity method and have to cover all scenarios. doThrow (): We can use doThrow () when we want to stub a void method that throws exception. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. For void methods, mockito provides a special function called doCallRealMethod () which can be used when you are trying to set up the mock. 1 2 doThrow (new Exception ()).when (mockObject).methodWhichThrowException (); Mockito's doCallRealMethod () can be used for void methods: @Test void whenAddCalledRealMethodCalled() { MyList myList = mock (MyList.class); doCallRealMethod ().when (myList).add (any (Integer.class), any (String.class)); myList.add ( 1, "real" ); verify (myList, times ( 1 )).add ( 1, "real" ); } How can we prove that the supernatural or paranormal doesn't exist? Now, if we don't want to simulate the processing of this method, this call itself is sufficient to mock the method. Here, we will just verify the captured value. WebUse doThrow() when you want to stub the void method to throw exception of specified class.. A new exception instance will be created for each method invocation. So how do we go about it? Is it suspicious or odd to stand by the gate of a GA airport watching the planes? Mockito doAnswer () method takes Answer as argument. What is a word for the arcane equivalent of a monastery? Can Martian regolith be easily melted with microwaves? Is there a proper earth ground point in this switch box? Analytical cookies are used to understand how visitors interact with the website. document.getElementById( "ak_js_1" ).setAttribute( "value", ( new Date() ).getTime() ); Your email address will not be published. Connect and share knowledge within a single location that is structured and easy to search. Unfortunately this doesn't work, as we receive the following compilation error: src/test/java/me/jvt/hacking/DataClassValidatorTest.java:24: error: 'void' type not allowed here Mockito.when (sut.doTheThing ()).thenThrow (new RuntimeException ("foo")); And in IntelliJ, we we see the following cryptic error: DevPedrada. Because, when() method of mockito works with return value and does not work when method is void. So how do I catch exception using catch-exception here? Find centralized, trusted content and collaborate around the technologies you use most. Mockito's doCallRealMethod () can be used for void methods: @Test void whenAddCalledRealMethodCalled() { MyList myList = mock (MyList.class); doCallRealMethod ().when (myList).add (any (Integer.class), any (String.class)); myList.add ( 1, "real" ); verify (myList, times ( 1 )).add ( 1, "real" ); } It lets us check the number of methods invocations. If you want your method to throw an exception, don't catch it, or catch it and throw a custom exception that wraps the original exception. A place where magic is studied and practiced? Throwing an Exception. These cookies track visitors across websites and collect information to provide customized ads. It lets us check the number of methods invocations. mockito throw exception void method java by DevPedrada on Dec 18 2020 Donate Comment 3 xxxxxxxxxx 1 doThrow(new Exception()).when(mockedObject).methodReturningVoid(); Source: stackoverflow.com Add a Grepper Answer Answers related to mockito void method throw exception throw doThrow() : We can use doThrow() when we want to stub a void method that throws exception. Please read and accept our website Terms and Privacy Policy to post a comment. Why do small African island nations perform better than African continental nations, considering democracy and human development? doThrow() : We can use doThrow() when we want to stub a void method that throws exception. Finally, be aware that you can doCallRealMethod() as well. }. Views. Source: (Example.java) import org.mockito.Mockito; import static org. Making statements based on opinion; back them up with references or personal experience. How Intuit democratizes AI development across teams through reusability. the exception won't be thrown from your test method). To learn more, see our tips on writing great answers. In Mockito we can use different methods to call real method or mock void method. How do you test that a Python function throws an exception? MathApplication makes use of calcService using its add method and the mock throws a RuntimeException whenever calcService.add () method is invoked. Thanks for contributing an answer to Stack Overflow! doThrow (): We can use doThrow () when we want to stub a void method that throws exception. I have always this error: Example Step 1 Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java @MariuszS response correctly answers what you are saying is unrelated to Mockito. In this article, we will show how to configure the method call to throw an exception using Mockito. What is the purpose of this D-shaped ring at the base of the tongue on my hiking boots? Stubbing void methods requires a different approach from when (Object) because the compiler does not like void methods inside brackets. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. Do you know how can I use Junit 4.13 when I'm using Spring Boot? Mockito provides following methods that can be used to mock void methods. Is it possible to rotate a window 90 degrees if it has the same length and width? Short story taking place on a toroidal planet or moon involving flying. Why are physically impossible and logically impossible concepts considered separate in terms of probability? For Example: Mockito. Popularity 9/10 Helpfulness 8/10 Source: stackoverflow.com. And you need to test to test that it does throw exception during the second method call, not the first one. The cookies is used to store the user consent for the cookies in the category "Necessary". Find a sample here: assert exception junit. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. 2 How do you throw an exception in PowerMock? Suppose we want to custom behavior a methods behavior based on the arguments passed then we can use doAnswer() API. 1 Answer Sorted by: 1 Firstly, your method deleteTableEsiti () never throws any exception. By clicking Accept all cookies, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. The cookie is used to store the user consent for the cookies in the category "Analytics". Linear regulator thermal information missing in datasheet, How to handle a hobby that makes income in US. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation. Manually raising (throwing) an exception in Python, throw checked Exceptions from mocks with Mockito. WebIn this recipe, we will stub a void method that doesn't return a value, so it throws an exception. How do you throw an exception in PowerMock? What Is the Difference Between 'Man' And 'Son of Man' in Num 23:19? Mockito.when(myService.doSomething()).thenThrow(new Exception("Cannot process")); then we will have following runtime exception: org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie We've added a "Necessary cookies only" option to the cookie consent popup. How do I open modal pop in grid view button? Why is printing "B" dramatically slower than printing "#"? How can I mock a void method to throw an exception? Note that we could not use the statement when().thenThrow() for methods that do not return any value. Follow Up: struct sockaddr storage initialization by network format-string. We also use third-party cookies that help us analyze and understand how you use this website. @JoeC yes, but: except for the most simple tests, you are probably doing things to do your test case-specific setup; depending upon what you're catching, one of these setup actions might throw the same exception, giving the impression your test passes, when in fact it doesn't. An easy and short way that worked for me was: Or if your exception is thrown from the constructor of a class: Unrelated to mockito, one can catch the exception and assert its properties. Sometimes it is necessary to call the real method from mocked object, in such case we need to use doCallRealMethod(), because doNothig() is the default behavior. Have you written a response to this post? Can airtags be tracked from an iMac desktop, with no iPhone? doThrow (): We can use doThrow () when we want to stub a void method that throws exception. Comment . How do you ensure that a red herring doesn't violate Chekhov's gun? This cookie is set by GDPR Cookie Consent plugin. WebIf this method fails (e.g. If you want your method to throw an exception, don't catch it, or catch it and throw a custom exception that wraps the original exception. Mockito + Catch-Exception + Assertj full sample, eu.codearte.catch-exception:catch-exception:2.0, http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html, static.javadoc.io/org.mockito/mockito-core/2.23.4/org/mockito/, How Intuit democratizes AI development across teams through reusability. It catches it and logs it, but always returns normally. Is it possible to create a concave light? cacheWrapper.putInSharedMemory ("key", "value"); EasyMock.expectLastCall ().andThrow (new RuntimeException ()); Check: http://easymock.org/api/org/easymock/internal/MocksControl.html#andVoid-- What are the effects of exceptions on performance in Java? How does claims based authentication work in mvc4? Do new devs get fired if they can't solve a certain bug? WebTry this for stubbing void methods to throw exceptions: EasyMock: // First make the actual call to the void method. 1 Answer Sorted by: 1 Firstly, your method deleteTableEsiti () never throws any exception. Annotate your test method with: Verify it has happened either by asserting that your test will throw such an exception: The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. WebIn this recipe, we will stub a void method that doesn't return a value, so it throws an exception. All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. @pringi Thanks, I see that the question concerned both mocking an exception and catching it. Before I start with my example, a bit about my setup: .lepopup-progress-100 div.lepopup-progress-t1>div{background-color:#e0e0e0;}.lepopup-progress-100 div.lepopup-progress-t1>div>div{background-color:#bd4070;}.lepopup-progress-100 div.lepopup-progress-t1>div>div{color:#ffffff;}.lepopup-progress-100 div.lepopup-progress-t1>label{color:#444444;}.lepopup-form-100, .lepopup-form-100 *, .lepopup-progress-100 {font-size:15px;color:#444444;font-style:normal;text-decoration:none;text-align:left;}.lepopup-form-100 .lepopup-element div.lepopup-input div.lepopup-signature-box span i{font-size:15px;color:#444444;font-style:normal;text-decoration:none;text-align:left;}.lepopup-form-100 .lepopup-element div.lepopup-input div.lepopup-signature-box,.lepopup-form-100 .lepopup-element div.lepopup-input div.lepopup-multiselect,.lepopup-form-100 .lepopup-element div.lepopup-input input[type='text'],.lepopup-form-100 .lepopup-element div.lepopup-input input[type='email'],.lepopup-form-100 .lepopup-element div.lepopup-input input[type='password'],.lepopup-form-100 .lepopup-element div.lepopup-input select,.lepopup-form-100 .lepopup-element div.lepopup-input select option,.lepopup-form-100 .lepopup-element div.lepopup-input textarea{font-size:15px;color:#444444;font-style:normal;text-decoration:none;text-align:left;background-color:rgba(255, 255, 255, 0.7);background-image:none;border-width:1px;border-style:solid;border-color:#cccccc;border-radius:0px;box-shadow:none;}.lepopup-form-100 .lepopup-element div.lepopup-input ::placeholder{color:#444444; opacity: 0.9;} .lepopup-form-100 .lepopup-element div.lepopup-input ::-ms-input-placeholder{color:#444444; opacity: 0.9;}.lepopup-form-100 .lepopup-element div.lepopup-input div.lepopup-multiselect::-webkit-scrollbar-thumb{background-color:#cccccc;}.lepopup-form-100 .lepopup-element div.lepopup-input>i.lepopup-icon-left, .lepopup-form-100 .lepopup-element div.lepopup-input>i.lepopup-icon-right{font-size:20px;color:#444444;border-radius:0px;}.lepopup-form-100 .lepopup-element .lepopup-button,.lepopup-form-100 .lepopup-element .lepopup-button:visited{font-size:17px;font-weight:700;font-style:normal;text-decoration:none;text-align:center;background-color:rgba(203, 169, 82, 1);background-image:linear-gradient(to bottom,rgba(255,255,255,.05) 0,rgba(255,255,255,.05) 50%,rgba(0,0,0,.05) 51%,rgba(0,0,0,.05) 100%);border-width:0px;border-style:solid;border-color:transparent;border-radius:0px;box-shadow:none;}.lepopup-form-100 .lepopup-element div.lepopup-input .lepopup-imageselect+label{border-width:1px;border-style:solid;border-color:#cccccc;border-radius:0px;box-shadow:none;}.lepopup-form-100 .lepopup-element div.lepopup-input .lepopup-imageselect+label span.lepopup-imageselect-label{font-size:15px;color:#444444;font-style:normal;text-decoration:none;text-align:left;}.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-tgl:checked+label:after{background-color:rgba(255, 255, 255, 0.7);}.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-classic+label,.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-fa-check+label,.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-square+label,.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-tgl+label{background-color:rgba(255, 255, 255, 0.7);border-color:#cccccc;color:#444444;}.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-square:checked+label:after{background-color:#444444;}.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-tgl:checked+label,.lepopup-form-100 .lepopup-element div.lepopup-input input[type='checkbox'].lepopup-checkbox-tgl+label:after{background-color:#444444;}.lepopup-form-100 .lepopup-element div.lepopup-input input[type='radio'].lepopup-radio-classic+label,.lepopup-form-100 .lepopup-element div.lepopup-input input[type='radio'].lepopup-radio-fa-check+label,.lepopup-form-100 .lepopup-element div.lepopup-input input[type='radio'].lepopup-radio-dot+label{background-color:rgba(255, 255, 255, 0.7);border-color:#cccccc;color:#444444;}.lepopup-form-100 .lepopup-element div.lepopup-input input[type='radio'].lepopup-radio-dot:checked+label:after{background-color:#444444;}.lepopup-form-100 .lepopup-element div.lepopup-input div.lepopup-multiselect>input[type='checkbox']+label:hover{background-color:#bd4070;color:#ffffff;}.lepopup-form-100 .lepopup-element div.lepopup-input div.lepopup-multiselect>input[type='checkbox']:checked+label{background-color:#a93a65;color:#ffffff;}.lepopup-form-100 .lepopup-element input[type='checkbox'].lepopup-tile+label, .lepopup-form-100 .lepopup-element input[type='radio'].lepopup-tile+label {font-size:15px;color:#444444;font-style:normal;text-decoration:none;text-align:center;background-color:#ffffff;background-image:none;border-width:1px;border-style:solid;border-color:#cccccc;border-radius:0px;box-shadow:none;}.lepopup-form-100 .lepopup-element-error{font-size:15px;color:#ffffff;font-style:normal;text-decoration:none;text-align:left;background-color:#d9534f;background-image:none;}.lepopup-form-100 .lepopup-element-2 {background-color:rgba(226,236,250,1);background-image:none;border-width:1px;border-style:solid;border-color:rgba(216,216,216,1);border-radius:3px;box-shadow: 1px 1px 15px -6px #d7e1eb;}.lepopup-form-100 .lepopup-element-3 * {font-family:'Arial','arial';font-size:26px;color:#333333;font-weight:normal;font-style:normal;text-decoration:none;text-align:center;}.lepopup-form-100 .lepopup-element-3 {font-family:'Arial','arial';font-size:26px;color:#333333;font-weight:normal;font-style:normal;text-decoration:none;text-align:center;background-color:transparent;background-image:none;border-width:1px;border-style:none;border-color:transparent;border-radius:0px;box-shadow:none;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;}.lepopup-form-100 .lepopup-element-3 .lepopup-element-html-content {min-height:36px;}.lepopup-form-100 .lepopup-element-4 * {font-family:'Arial','arial';font-size:19px;color:#555555;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;}.lepopup-form-100 .lepopup-element-4 {font-family:'Arial','arial';font-size:19px;color:#555555;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;background-color:transparent;background-image:none;border-width:1px;border-style:none;border-color:transparent;border-radius:0px;box-shadow:none;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;}.lepopup-form-100 .lepopup-element-4 .lepopup-element-html-content {min-height:63px;}.lepopup-form-100 .lepopup-element-5 * {font-family:'Arial','arial';font-size:13px;color:#555555;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;}.lepopup-form-100 .lepopup-element-5 {font-family:'Arial','arial';font-size:13px;color:#555555;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;background-color:transparent;background-image:none;border-width:1px;border-style:none;border-color:transparent;border-radius:0px;box-shadow:none;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;}.lepopup-form-100 .lepopup-element-5 .lepopup-element-html-content {min-height:60px;}.lepopup-form-100 .lepopup-element-6 * {font-family:'Arial','arial';font-size:13px;color:#333333;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;}.lepopup-form-100 .lepopup-element-6 {font-family:'Arial','arial';font-size:13px;color:#333333;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;background-color:transparent;background-image:none;border-width:1px;border-style:none;border-color:rgba(216,216,216,1);border-radius:0px;box-shadow:none;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;}.lepopup-form-100 .lepopup-element-6 .lepopup-element-html-content {min-height:auto;}.lepopup-form-100 .lepopup-element-0 * {font-size:15px;color:#ffffff;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;}.lepopup-form-100 .lepopup-element-0 {font-size:15px;color:#ffffff;font-weight:normal;font-style:normal;text-decoration:none;text-align:left;background-color:#5cb85c;background-image:none;border-width:0px;border-style:solid;border-color:#ccc;border-radius:5px;box-shadow: 1px 1px 15px -6px #000000;padding-top:40px;padding-right:40px;padding-bottom:40px;padding-left:40px;}.lepopup-form-100 .lepopup-element-0 .lepopup-element-html-content {min-height:160px;}. 4.2. public void deleteCurrentlyLoggedInUser (Principal principal) { if (findLoggedInUser (principal) == null) { throw new UserAlreadyDeletedException (); } userRepository.delete (findLoggedInUser (principal)); } Here is findLoggedInUser: User findLoggedInUser (Principal principal) { return userRepository.findByUsername I wonder though if this depends on any behaviour of the code under test. WebIt doesn't return a value, so it throws an exception. WebHere we've added an exception clause to a mock object. Difficulties with estimation of epsilon-delta limit proof. rev2023.3.3.43278. Has this content helped you? To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception. WebIf this method fails (e.g. Testers can reuse or extend one of the provided Rules below, or write their own. The thing is that stubbing a Unit method only makes sense if you wanna make it throw an exception, otherwise the only thing you want out of it is to verify it was called as you mentioned. Heres a simple dictionary class well use in these examples: Have a look at how to test if an exception was thrown using JUnit. on Tue, 18 Jan 2022 15:28:31 UTC, and last updated on Tue, 18 Jan 2022 15:28:31 UTC. It has a void eat() method which the customer object will call when served with the dish. Invalid: java.lang.Exception: Cannot process at Getting ready For this recipe, our system under test will be a PersonProcessor class that, for simplicity, does only one thing: it delegates the process of saving person to the PersonSaver class. Mutually exclusive execution using std::atomic? To subscribe to this RSS feed, copy and paste this URL into your RSS reader. Not the answer you're looking for? Why are physically impossible and logically impossible concepts considered separate in terms of probability? Here, we configured an add () method which returns void to throw IllegalStateException when called. mockito. doAnswer (): We can use this to perform some operations when a mocked object method is called that is returning void. Using mockito, you can make the exception happen. Why did Ukraine abstain from the UNHRC vote on China? To subscribe to this RSS feed, copy and paste this URL into your RSS reader. Source: (Example.java) import org.mockito.Mockito; import static org. In mocking, for every method of mocked object doNothing is the default behavior. PowerMockito is a superset (or more of a supplement) that can be used with both these frameworks. The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional". Following all codes perform similar behavior, We can do different things with argument capture. Now, we want to write unit test for UserService class and mock userRepository.But the only thing we need to verify in this test case is that updateName() method from userRepository is called with correct set of parameters.For this purpose we need to mock updateName() method, capture the arguments and verify the arguments. Source: (Example.java) import org.mockito.Mockito; import static org. Let me know the URL: Do you not have a website set up with WebMention capabilities? Is a PhD visitor considered as a visiting scholar? As with many other Java developers, I heavily utilise Mockito as a mocking framework for unit testing. We will present two approaches: one for methods that returns some value and one for void methods - there are some differences in the implementation. Customer: Dish: 1 2 3 4 5 package com.javacodegeeks.mockito; public interface Dish { void eat () throws WrongDishException; } 2. Asking for help, clarification, or responding to other answers. In this recipe, we will stub a void method. Make the exception happen like this: when (obj.someMethod ()).thenThrow (new AnException ()); Verify it has happened either by asserting that your test will throw such an exception: @Test (expected = AnException.class) Or by normal mock verification: verify (obj).someMethod (); Making a mocked method return an argument that was passed to it. Non-Void Return Type First, if our method return type is not void we can use when ().thenThrow (): How can I mock a void method to throw an exception? Not the answer you're looking for? Using indicator constraint with two variables. If you're using JUnit 4, you can annotate your test with, to assert that an exception has occured. doThrow () : Throw exception when mocked void method is called doCallRealMethod () : Do not mock and call real method 1) Using doNothing () If we just want to completely ignore the void method call, we can use doNothing (). By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. How do you assert that a certain exception is thrown in JUnit tests? WebVoid method throws an exception Question: Write a java program that uses Mockito on a method that returns a void and throws an exception. What this will do, is call the real void method with the actual arguments. Hey guys! WebVoid method throws an exception Question: Write a java program that uses Mockito on a method that returns a void and throws an exception. To do this we make use of doThrow () method of Mockito class. Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. You also have the option to opt-out of these cookies. Why are physically impossible and logically impossible concepts considered separate in terms of probability? mockito. Other than that we can also make use of doNothing () and doAnswer () APIs. Stubbing it with a Unit value to leverage on the strict mode could be done, but it feels quite hacky, the point of strict mode is to avoid repeating yourself By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. Mockito provides us with a verify()method that lets us verify whether the mock void method is being called or not. I have tried lot of ways to do this but none of them work. 2. Browse Library. It doesn't return a value, so it throws an exception. Also, no need for any kind of .replay() with Mockito, which is very nice! Method that I'm testing returns void and I just can't seem to find a way to assert that exception was found. WebIt doesn't return a value, so it throws an exception. Save my name, email, and website in this browser for the next time I comment. Can airtags be tracked from an iMac desktop, with no iPhone? Does Counterspell prevent from any further spells being cast on a given turn? // Create a CacheWrapper spy and stub its method to throw an exception. mockito. Mockito: Trying to spy on method is calling the original method. if the method someMethod() return type is void, then it does not work like this. For Example: Mockito. Here, we configured an add () method which returns void to throw IllegalStateException when called. We will present two approaches: one for methods that returns some value and one for void methods - there are some differences in the implementation. Both are different frameworks. 1 2 doThrow (new Exception ()).when (mockObject).methodWhichThrowException (); March 23rd, 2015 0 How to convert Character to String and a String to Character Array in Java, java.io.FileNotFoundException How to solve File Not Found Exception, java.lang.arrayindexoutofboundsexception How to handle Array Index Out Of Bounds Exception, java.lang.NoClassDefFoundError How to solve No Class Def Found Error. It catches it and logs it, but always returns normally. What am I doing wrong here in the PlotLegends specification? This cookie is set by GDPR Cookie Consent plugin. If you're using Java 8, and can use JUnit 4.13 or later, you can use assertThrows: If you're going to migrate all of your code to something, this seems like a better long-term bet. JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by domain experts, articles, tutorials, reviews, announcements, code snippets and open source projects. Is it suspicious or odd to stand by the gate of a GA airport watching the planes? If you are new to mocking you can know more at mockito website. The project has dependencies for PowerMock and EasyMock. If you ever wondered how to do it using the new BDD style of Mockito: willThrow (new Exception ()).given (mockedObject).methodReturningVoid ()); And for future reference one may need to throw exception and then do nothing: willThrow (new Exception ()).willDoNothing ().given (mockedObject).methodReturningVoid ()); Share Other than that we can also make use of doNothing() and doAnswer() APIs. Thanks for contributing an answer to Stack Overflow! In this recipe, we will stub a void method. 2. The PowerMockito. For example there is an object method that throws exception if you call it the second time. The problem is when trying to mock putInSharedMemory method because is void. This means we have work with the following methods to mock a void method: doThrow (Throwable) doThrow (Class) doAnswer (Answer) doNothing () doCallRealMethod () This is the class we will be using for the examples. If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito: If you're using JUnit 4, and Mockito 1.10.x To do this we make use of doThrow () method of Mockito class. this does not work if the method doSomething() return type is void? If a law is new but its interpretation is vague, can the courts directly ask the drafters the intent and official interpretation of their law? Mockito provides following methods that can be used to mock void methods. Has 90% of ice around Antarctica disappeared in less than a decade?