0

My test automation scripts have setup() and tearDown() methods. In my setup(), I have few pre-requisites specified which will require by rest of the tests.

Now, in my setup() method I want to specify a function, which will fail the build if condition is not meeting. E.g.

   try {
        // To do 
    } catch (Exception e) {
          failJenkinsBuild();
    }

I have gone through couple of solution but none specifies how to do it in Java?

  1. Fail a Jenkins build from groovy script
  2. Abort current build from pipeline in Jenkins
paul
  • 4,333
  • 16
  • 71
  • 144
  • Possible duplicate of [Failing a jenkins job](https://stackoverflow.com/questions/15650265/failing-a-jenkins-job) ([First answer](https://stackoverflow.com/a/15650672/10433739)) - basically just call `System.exit(anything but zero)` – Benjamin Urquhart Apr 25 '19 at 18:34
  • It looks like these are *inside your code being built*, not the control script for the build (which is what you're linking to). Generally, you set Jenkins builds to fail if any of the tests fail, so just fail your test. – chrylis -cautiouslyoptimistic- Apr 25 '19 at 18:37
  • @BenjaminUrquhart I wonder if it was this easy `Sytem.exit(-1)` then what these people discussing in these SO posts? PS: I will try your suggestion and accept `That solved my problem` – paul Apr 25 '19 at 18:42

2 Answers2

0

You can use try-catch and throw error at catch to fail the build when there is an error.

try {
     // To Do
} catch(Exception e) {
    throw e
}
veekaly
  • 240
  • 3
  • 9
0

This is what the "error" step is used for. It can send a message AND it also fails the build. It can be used ANYWHERE, not just in an exception.

In fact, if you do not CATCH an exception it should also fail the build.

   try {
        // Your test here 
   } catch (Exception e) {
        error("Something bad happened. Failing this build.")
   }

Warning: Catching ALL exceptions can cause unexpected behavior. For example catching a user abort exception and NOT rethrowing an exception (or using error) may prevent you from aborting a build.