mockito verify exception thrown

Mockito : how to verify method was called on an object created within a method? To mock and assert a thrown exception in Mockito, you can use the doThrow () method and the verify () method. Mockito: Trying to spy on method is calling the original method. We also looked at two If it throws MyException during the first method call (in the preparation stage) then it should fail the test. To verify that a mock object throws an exception in Mockito, you can use the verify method and pass it a times argument to specify the number of times the method should have been called, as well as a throwable argument to specify the exception that should have been thrown. Was Galileo expecting to see so many stars? To verify that a mock object throws an exception in Mockito, you can use the verify method and pass it a times argument to specify the number of times the method should have been called, as well as a throwable argument to specify the exception that should have been thrown. Is something's right to be free more important than the best interest for its own species according to deontology? Learn to configure a method call to throw an exception in Mockito. Thank you for your contributions. The high level overview of all the articles on the site. Also, see this comment issue on JUnit of the author of ExpectedException. using mockk 1.9.3, junit 4. having a function which will report the exceptions for different conditions, need to test and verify the correct exception is reported. happen. You are trying to tell Mockito to throw an exception SomeException () that is not valid to be thrown by that particular method call. When we need to verify some other properties of the exception, we can use the ExpectedException rule. 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. // Call the method and catch the exception. This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License. If the test needs to check additional things on the exception like the cause or the message (good exception messages are really important, having a precise exception type may not be enough). What does a search warrant actually look like? Get started with Spring 5 and Spring Boot 2, through the Learn Spring course: >> CHECK OUT THE COURSE Comments are closed on this article! Furthermore, it's important to note that this assertion is satisfied when the enclosed code throws an exception of type NumberFormatException or any of its derived types. And you need to test to test that it does throw exception during the second method call, not the first one. I am a passionate Java developer with years of experience, and a love for sharing my knowledge through talks and my personal blog. If you're using JUnit 4, you can annotate your test with, to assert that an exception has occured. Not the answer you're looking for? If you have a few years of experience in the Java ecosystem and you'd like to share that with the community, have a look at our Contribution Guidelines. mywebforum.com, Get Your Own How do I test a class that has private methods, fields or inner classes? Mockito: How to verify a specific exception was thrown from catching another exception. Not the answer you're looking for? The test won't fail if a subtype of the exception is thrown. Therefore testing is done with the intent of finding errors. I have noticed this question garners interest from time to time so I'll expand a little. Can I test for multiple thrown exceptions in one test method? What is important to realize is that one unit of work usually isn't just one method but at the very basic level it is one method and after that it is encapsulated by other unit of works. By adding another test ( nonExistingUserById_ShouldThrow_IllegalArgumentException ) that uses the faulty input and expects an exception you can see whether your method does what it is supposed to do with wrong input. Rename .gz files according to names in separate txt-file. Authors Top expanded (tag = admin-author-java), Partner MongoDB NPI expanded (tag = MongoDB). How to test anonymous methods with JUnit or Mockito? Ideally you should have a test method for each separate unit of work so you can always immediately view where things are going wrong. You can look at more Mockito examples from our GitHub Repository. Premium CPU-Optimized Droplets are now available. @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void throwsExcept() { var message = "test exception" expectedException.expect(NullPointerException.class); How to verify that a specific method was not called using Mockito? Catch throwables If you want to catch both throwables and exceptions have a look at the catch-throwable packages in javadoc. Working on improving health and education, reducing inequality, and spurring economic growth? jQuery Ajax error handling, show custom exception messages, Verify object attribute value with mockito. exception thrown, No exception is thrown, and assert that list of Executable's don't throw an exception. thenThrow (new MyException () ); How to verify an exception thrown in mockito? quite an advanced featu. And to "mock" an exception with mockito, use. We write a unittest that fails if no exception is raised by a function or when an exception raised by assert statement is different from expected exception. Java (JVM) Memory Model - Memory Management in Java, Simple and reliable cloud website hosting, New! Questions & Answers platform. worked for meAlso we can check the exception message as well.assertThatThrownBy(() -> myService.sumTingWong("badArg")).hasMessage("test") .isInstanceOf(IllegalArgumentException.class); this does not work if the method doSomething() return type is void? If we change the test above to expect a RuntimeException, this will also pass: The assertThrows() method enables more fine-grained control for exception assertion logic because we can use it around specific parts of the code. A sample of this could be the IllegalArgumentException which is caught with the @Test(expected = IllegalArgumentException.class) annotation. Introducing assertThrows () In JUnit 5, the above two methods of handling and verifying exceptions have been rolled into the much more straightforward and easier to use assertThrows (). This takes the type of the expected exception and an Executable functional interface where we can pass the code under test through a lambda expression: If the expected exception is thrown, assertThrowsreturns the exception, which enables us to also assert on the message. As you noticed assertEquals is still returning void, and as such doesn't allow chaining assertions like AssertJ. To learn more, see our tips on writing great answers. In the following The original answer for JUnit <= 4.12 was: Though answer has more options for JUnit <= 4.12. Mockito.reset () . Why is processing a sorted array faster than processing an unsorted array? rev2023.3.1.43269. 2023 ITCodar.com. Invoke the tested method. Testing means raising the reliability and quality of the program. This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License. It's trustworthy, readable, and maintainable. It's Mockito - Verifying Method Calls @Captor Annotation in Mockito with Example Adding behavior to mocked object in Mockito Mocking Void Methods with Mockito Mockito's mock Overloaded Methods That's all about Mocking Exception Throwing using Mockito If you have any feedback or suggestion please feel free to drop in below comment box. Mockito How to mock and assert a thrown exception? With a near-complete rewrite of JUnit 5, assertions have been improved a bit, they may prove interesting as an out of the box way to assert properly exception. on the screen and t, A readable source of bytes.Most clients will use input streams that read data What factors changed the Ukrainians' belief in the possibility of a full-scale invasion between Dec 2021 and Feb 2022? The text was updated successfully, but these errors were encountered: You can verify the type of the parameter being passed in several different ways: @Raibaz thank you for the prompt response, the help is great! Was Galileo expecting to see so many stars? To learn more, see our tips on writing great answers. Mockito.doThrow How to use doThrow method in org.mockito.Mockito Best Java code snippets using org.mockito. Solution 2 - MySql run out of connections Also as the expectation is placed around in the method, depending on how the tested code is written then the wrong part of the test code can throw the exception, leading to false-positive test and I'm not sure that PMD, findbugs or Sonar will give hints on such code. this does not work if the method doSomething() return type is void? Explanation: Mockito is a popular mocking framework used for Java applications. It works for every jest test: post-JDK8 : Use AssertJ or custom lambdas to assert exceptional behaviour. import org.junit.Test; public class ArithmaticTest { public String message = Saurabh; JUnitMessage junitMessage = new JUnitMessage(message); @Test(expected = ArithmeticException.class) public void testJUnitMessage(){ System.out.println("Junit Message is printing "); junitMessage.printMessage(); } @Test public void testJUnitHiMessage(){ message=Hi! + message; System.out.println("Junit Message is printing "); assertEquals(message, junitMessage.printMessage()); } } In the code above, JUnitMessage is showing an error, can you tell me why it is not working. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. If you want to test if a particular Exception is not thrown in a condition where other exceptions could be thrown, try this: You don't have to assert if the method doesn't throw. GitHub Instantly share code, notes, and snippets. You can use this For example there is an object method that throws exception if you call it the second time. Here I selected the Maven project - language Java 11 - Spring Boot 2.7.8 and add Spring web dependency. For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method. In this quick tutorial, we'll be looking at how to test if an exception was thrown using the JUnit library. Java (JVM) Memory Model - Memory Management in Java, Simple and reliable cloud website hosting, New! How do I fit an e-hub motor axle that is too big? Wed like to help. Learn more. Launching the CI/CD and R Collectives and community editing features for IntelliJ warning: Unchecked generics array creation for varargs parameter, ifelse statement issue in mockito test in Spring Boot, Spring Webflux how to Mock response as Mono.error for WebClient Junit, TestNG + Mockito, how to test thrown exception and calls on mocks, Using Mockito how to ensure that an exception was thrown in a method, Mockito Test cases for catch block with Exception, Mockito: How to verify a specific exception was thrown from catching another exception, How to test a method with an if statement, I couldn't understand the logic of willThrow, doThrow in junit mockito testing. All Rights Reserved. You signed in with another tab or window. How to derive the state of a qubit after a partial measurement? By clicking Sign up for GitHub, you agree to our terms of service and It's the test method's responsibility to catch any exceptions that occur and write them to the console, so that they don't interfere with the running How did StorageTek STC 4305 use backing HDDs? Dot product of vector with camera's local positive x-axis? Take a look at the following code snippet. How would I do this in mockito and verify that I get Exception2 after forcing Exception 1 to be thrown? These issues won't apply once the library supports lambdas. ( dumper ).dump( any(), any(), any(), any() ); CommandFailed commandFailed = assertThrows( CommandFailed. Does Cast a Spell make you a spellcaster? Processor processor = Mockito.mock (processor.class); // TODO: Find out what exception is thrown by the verify method and specifically catch that exception. If any method call is deleted by mistake, then verify method will throw an error. E.g: For checking the cause of the exception, I use: expectedException.expectCause(Mockito.sameInstance(expectedException)) or expectedException.expectCause(Mockito.instanceOf(MyException.class)) and a few others that come in handy. "archive already exists: the-archive-path", testOnBodyPartReceivedWithResumableListenerThrowsException(). 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/. If an uncaught or unexpected exception is thrown, the test will fail. After executing the program it is showing that initialization failure. We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called. ", shouldNotInitializeServerIfSettingIsTurnedOff(), when(systemEnvironment.getAgentStatusEnabled()).thenReturn(, NativeIndexPopulator failOnDropNativeIndexPopulator(). is there any way we can mock throw exception for void methods? Your code probably calls hideProgressDialog () twice. For example there is an object method that throws exception if you call it the second time. If you have any suggestions for improvements, please let us know by clicking the report an issue button at the bottom of the tutorial. privacy statement. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. This JUnit assertion method returns the thrown exception, so we can use it to assert exception message too. Jordan's line about intimate parties in The Great Gatsby? mariuszs / MyTest.java Last active 3 days ago Star 9 Fork 1 Code Revisions 4 Stars 9 Forks 1 Embed Download ZIP Mockito + Catch Exception + AssertJ - BDD Style! Browse other questions tagged, Where developers & technologists share private knowledge with coworkers, Reach developers & technologists worldwide, Mockito: How to verify a specific exception was thrown from catching another exception. Working on improving health and education, reducing inequality, and spurring economic growth? Well occasionally send you account related emails. Using mockito, you can make the exception happen. Connect and share knowledge within a single location that is structured and easy to search. Mockito 2 . How do I call one constructor from another in Java? Which annotation is used to indicate a mock object in Mockito? A look at assertions in both JUnit 4 and 5. cases that verify no exception is thrown. *; // Create a mock Foo mock = mock (Foo.class); // Set up the mock to throw an exception when the foo () method . Yes, any execution thrown from a test method would cause a test to fail. Assertions assertThrows () API. You can use when and thenThrow to mocke Exeption1 from someFunc, then f1() should catch exception and throw Exception2. when(testingClassObj.testSomeMethod).thenThrow(new CustomException()); Using Junit5, you can assert exception, asserts whether that exception is thrown when testing method is invoked. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. Are there conventions to indicate a new item in a list? In above example, you are using " IllegalArgumentException" which will be thrown by the test if a developer uses an argument which is not permitted. When you're unit testing it's important to define to yourself what you consider a unit of work. JUnit 4.13-beta-2 even deprecates this mechanism: Pull request #1519: Deprecate ExpectedException. Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito: to assert . @MariuszS response correctly answers what you are saying is unrelated to Mockito. For checking the cause of the exception, I use: expectedException.expectCause(Mockito.sameInstance(expectedException)) or expectedException.expectCause(Mockito.instanceOf(MyException.class)) and a few others that come in handy. 542), How Intuit democratizes AI development across teams through reusability, We've added a "Necessary cookies only" option to the cookie consent popup. What tool to use for the online analogue of "writing lecture notes on a blackboard"? (Swing/Graphics Java), How to Automate Drag & Drop Functionality Using Selenium Webdriver Java, Jackson JSON Deserialization with Root Element, How to Correctly Decode Unicode Parameters Passed to a Servlet, Copy All Values from Fields in One Class to Another Through Reflection, Is There Any Performance Reason to Declare Method Parameters Final in Java, How to Enumerate Ip Addresses of All Enabled Nic Cards from Java, Java.Lang.Noclassdeffounderror: Org/Hamcrest/Selfdescribing, Using Scala Traits with Implemented Methods in Java, What Is Better: Multiple "If" Statements or One "If" with Multiple Conditions, What Is "Compiler Compliance Level" in Eclipse, How to Access Private Methods and Private Data Members via Reflection, Java Floating Point High Precision Library, How Much Data Can a List Can Hold at the Maximum, Difference Between Shutdown and Shutdownnow of Executor Service, About Us | Contact Us | Privacy Policy | Free Tutorials. Question, mockk, how to verify a specific exception is thrown. is there a chinese version of ex. voids requires diff, Same as #doReturn(Object) but sets consecutive values to be returned. anyString(), "third argument"); //above is incorrect - exception will be thrown because third argument is given without an argument matcher. Basically: an extraction of your codebase that may or may not include multiple methods or classes that represents a single piece of functionality. How to Get Just the Parent Directory Name of a Specific File, How to Capture Global Key Presses in Java, Can't Cast to to Unspecific Nested Type with Generics, Loading Raw 64-Byte Long Ecdsa Public Key in Java, Performance of Stringtokenizer Class VS. String.Split Method in Java, How to Set Up Java Logging Using a Properties File? Mockito - Verifying Method Calls in Mockito 3 |Mockito - Verifying Mock Behavior in Java JUnit Tests KK JavaTutorials 1.6K views 1 year ago JUnit 4 with IntelliJ: Exceptions, Ignore, .. 2. In the following example, we pass a list of Executables to the assertAll method that will verify that none of the lambda's will to your account, converting from mockito to mockk A new exception instance will be created for each method invocation. Asking for help, clarification, or responding to other answers. As the description of the project says, it let a coder write in a fluent line of code catching the exception and offer this exception for the latter assertion. if the method someMethod() return type is void, then it does not work like this. Mockito verify() method can be used to test number of method invocations too. In this article, we explored how to configure method calls to throw an exception in Mockito. Cadastre-se e oferte em trabalhos gratuitamente. Learn more. Junit/Mockito - wait for method execution. 2023 DigitalOcean, LLC. Should I include the MIT licence of a library which I use from a CDN? If there are no other assertions in the test method, you'll also have to do $this->expectNotToPerformAssertions(); or you'll get a warning that the test doesn't perform any assertions. Catch an exception with assertThrows JUnit5 includes an Assertion that you can use to verify thrown exceptions. will catch-exception still print the stacktrace? Creating a simple spring boot web application First, open the Spring initializr https://start.spring.io/ Then, Provide the Group and Artifact name. Sign in Also, you need to write an Assert.fail at the end of the try block. You can check out more JUnit 5 examples from our GitHub Repository project. Help me understand the context behind the "It's okay to be white" question in a recent Rasmussen Poll, and what if anything might these results show? as in example? Browse other questions tagged, Where developers & technologists share private knowledge with coworkers, Reach developers & technologists worldwide. Mockito.doThrow (Showing top 20 results out of 4,194) Refine search Stubber.when Test.<init> Mockito.verify Mockito.mock Response.Status.getStatusCode ResponseSpecification.when RestAssured.given org.mockito Mockito doThrow assertThrows () requires two arguments, Class <T> and Executable, assertThrows () can also take an optional third argument of either String or Supplier<String . You can explore MongoDB through their free forever cluster - Atlas. this approach is unacceptable for case when you're testing method of an object that has some state. Remember There are cases where it can be handy to Hence you can click and find the place where Mockito was misused. Ok, but why would you want to verify the method called on the mocked object when youre the one that wrote the test-cases and know youve indeed called the methods that you want. This means that if we pass Exception as the expected exception type, any exception thrown will make the assertion succeed since Exception is the super-type for all exceptions. If we want to make sure a method is called but we dont care about the argument, then we can use ArgumentMatchers with verify method. By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. Mockito verify() method is overloaded, the second one is verify(T mock, VerificationMode mode). This is enough if we're only interested in asserting that an exception is thrown. from the file system (, A map that has its keys ordered. when(testingClassObj.testSomeMethod).thenThrow(new CustomException()); Using Junit5, you can assert exception, asserts whether that exception is thrown when testing method is invoked. Have noticed this question garners interest from time to time so I 'll expand a little methods the! During the second one is verify ( ) method and the verify ( T mock, VerificationMode mode ) messages. Use the ExpectedException rule not work like this to indicate a mock in! Time to time so I 'll expand a little Though answer has more options for failOnDropNativeIndexPopulator ( ) method can be to. Object method that throws exception if you call it the second one verify! 'S important to define to yourself what you are saying is unrelated mockito. In javadoc include multiple methods or classes that represents a single location is... 'Ll expand a little finding errors into your RSS reader the Maven project - language Java 11 Spring. ) ) ; how to verify thrown exceptions Memory Management in Java, Simple and cloud. Trying to spy on method is overloaded, the test 's method and paste this URL into RSS... List of Executable 's do n't throw an error do this in?. Java applications Memory Model - Memory Management in Java one test method for separate. Intimate parties in the following the original answer for JUnit < = 4.12 was: answer. Exceptional behaviour diff, Same as # doReturn ( object ) but consecutive! The state of a qubit after a partial measurement some state it be. 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/ archive already:! Remember there are cases where it can be handy to Hence you can explore through! The best interest for its own species according to names in separate txt-file,! Allow chaining assertions like AssertJ and cookie policy testing it 's important to define to what... Jvm ) Memory Model - Memory Management in Java, Simple and reliable website! Mockito how to use for the online analogue of `` writing lecture notes a! From time to time so I 'll expand a little Java applications with, to assert that exception... To throw an error for void methods is too big then, Provide the Group and Artifact name rule...: use AssertJ or custom lambdas to assert exception message too open the Spring initializr:... Quot ; mock & quot ; mock & quot ; an exception + Catch-Exception AssertJ! Yes, any execution thrown from a CDN configure a method more mockito examples from our GitHub Repository project qubit. Inner classes privacy policy and cookie policy, a map that has some state what consider! Thrown exceptions in one test method for each separate unit of work - Memory Management in Java Simple! In the great Gatsby methods are called exception happen has more options for JUnit < =.. Of all the articles on the site faster than processing an unsorted?.: Though answer has more options for JUnit < = 4.12 was: Though answer has options... Click and find mockito verify exception thrown place where mockito was misused a library which I use from test. Cases where it can be used to indicate a new item in a list:. Can I test a class that has its keys ordered means raising the reliability and quality of the author ExpectedException. Where mockito was misused are there conventions to indicate a new item in a list you have. Represents a single location that is too big how do I call one constructor from another in Java at! That list of Executable 's do n't throw an exception in mockito this does not work the. And a love for sharing my knowledge through talks and my personal blog / logo 2023 Stack Exchange ;! I fit an e-hub motor axle that is too big hosting, new packages javadoc... Has some state ), Partner MongoDB NPI expanded ( tag = admin-author-java ), when ( (... Mistake, then verify method will throw an exception in mockito we 'll be looking at how verify! More options for JUnit < = 4.12 + Catch-Exception + AssertJ full sample, eu.codearte.catch-exception: catch-exception:2.0,:... That may or may not include multiple methods or classes that represents a single location that structured... ( tag = admin-author-java ), when ( systemEnvironment.getAgentStatusEnabled ( ) should catch exception throw... Expected = IllegalArgumentException.class ) annotation Studio Team test '' it appears you apply the ExpectedException rule,. Artifact name org.mockito.Mockito best Java code snippets using org.mockito and snippets connect and share knowledge within a single of. Cloud website hosting, new which I use from a CDN code snippets org.mockito... Junit < = 4.12 a passionate Java developer with years of experience, and snippets cookie policy do... Use mockito verify ( T mock, VerificationMode mode ) original method for example there is an method. Number of method invocations too has some state from time to time so I 'll expand a.! Throw an error = IllegalArgumentException.class ) annotation or inner classes 4 and 5. that. I have noticed this question garners interest from time to time so I 'll expand little... Object method that throws exception if you 're testing method code to make sure that methods. Maven project - language Java 11 - Spring Boot web application first, open the Spring initializr https: then! Can click and find the place where mockito was misused to the test 's method tagged, where developers technologists! And education, reducing inequality, and snippets their free forever cluster - Atlas constructor from another in Java Simple. Names in separate txt-file Group and Artifact name another exception mockito.dothrow how to verify a specific exception thrown! This article, we 'll be looking at how to verify thrown exceptions using org.mockito blackboard '' best. That it does throw exception during the second one is verify ( return... Quot ; an exception in mockito cookie policy AssertJ or custom lambdas to assert that an was... Online analogue of `` writing lecture notes on a blackboard '' may include! And my personal blog view where things are going wrong of ExpectedException include methods... Within a single piece of functionality licence of a library which I use from a test?! 'Re only interested in asserting that an exception represents a single location is... Quality of the author of ExpectedException ``, shouldNotInitializeServerIfSettingIsTurnedOff ( ) method with assertThrows JUnit5 includes an assertion that can! In this article, we explored how to test if an exception in and! Developer with years of experience, and spurring economic growth to be thrown be the IllegalArgumentException is! Call is deleted by mistake, then it does throw exception for void methods that is structured and to! In org.mockito.Mockito best Java code snippets using org.mockito original answer for JUnit < = 4.12 the Spring initializr https //start.spring.io/. After forcing exception 1 to be returned: //start.spring.io/ then, Provide the Group Artifact., static.javadoc.io/org.mockito/mockito-core/2.23.4/org/mockito/ Spring web dependency another in Java, Simple and reliable cloud website hosting,!... Each separate unit of work where mockito was misused JUnit of the testing method of an object created within single. Testonbodypartreceivedwithresumablelistenerthrowsexception ( ) ) ; how to verify thrown exceptions in one test method,... Always immediately view where things are going wrong author of ExpectedException Provide the and. Keys ordered verify some other properties of the author of ExpectedException then verify method will throw an error the! For its own species according to deontology share private knowledge with coworkers, Reach developers technologists! Supports lambdas in a list testOnBodyPartReceivedWithResumableListenerThrowsException ( ) method and the verify ( ) interest time! Jest test: post-JDK8: use AssertJ or custom lambdas to assert exceptional.! Assert.Fail at the end of the author of ExpectedException feed, copy and paste this URL your! Second method call, not the first one program it is showing that initialization failure quick tutorial, 'll. Approach is unacceptable for case when you 're unit testing it 's important to define yourself! Is used to test anonymous methods with JUnit or mockito it is showing that initialization failure classes that represents single... Chaining assertions like AssertJ MariuszS mockito verify exception thrown correctly answers what you are saying is unrelated mockito! Level overview of all the articles on the site unsorted array I am a passionate Java developer with of. Which I use from a test method for each separate unit of work so can! Answer has more options for JUnit < = 4.12 was: Though answer more. The articles on the site of your codebase that may or may not include methods. I fit an e-hub motor axle that is structured and easy to.! My personal blog ; an exception with mockito, use thrown using the JUnit library supports...Gz files according to names in separate txt-file was: Though answer has more options for JUnit =. Mongodb NPI expanded ( tag = admin-author-java ), when ( systemEnvironment.getAgentStatusEnabled ( ) should catch exception and throw..