If you are working with Jenkins Shared libraries, you may be missing out on what in my opinion is a great way to structure and test your project. I found a great blog post that explains how to do it (link below).
When you work with Jenkins pipelines, soon enough your Jenkins file will get messy. If you have a team working on the same project, it becomes a pull request race where everyone is rushing to push their code to master and avoid merge hell. Add multiple projects to the mix, and you now have to deal with duplicate code and different ways of doing things. Then there is the problem of testing the Groovy code, which is always an issue and almost always done by just brute-forcing Jenkins jobs (Hope that you are using the replay button)
Ahh, the glamorous DevOps life..
Jenkins Share Libraries solve most of the above problems:
- Developers don’t step on each other’s toes and can work on their own classes.
- The Jenkinsfile itself is much cleaner
- Keep the DRY principle
- Allow you to enforce a uniform pipeline structure even if you have one project that runs NodeJs and another one in Java
What is missing from the points above is unit testing. With JenkinsPipelineUnit pretty much abandoned as of the time of writing, testing you Shared Libraries is not that straight forward.
When I began working with Shared Libraries, almost everything went under the vars folder. It just worked, and I didn’t give it much thought until I wanted to implement unit testing to my code.
Here is how the code folder structure looks for a shared library:
+- src # Groovy source files
| +- org
| +- foo
| +- Bar.groovy # for org.foo.Bar class
| +- foo.groovy # for global 'foo' variable
| +- foo.txt # help for 'foo' variable
+- resources # resource files (external libraries only)
| +- org
| +- foo
| +- bar.json # static helper data for org.foo.Bar
Like others, I pretty much ignored the src folder which at retrospect was a mistake.
After digging around looking for a better way to test my code, I found a blog post by Adrian Kuper, that offers a structure for the Shared Library which allows you to run unit tests with JUnit and even use mocks.
A GitHub example: jenkins-shared-library-example
The idea is to keep the steps under “var” as simple as possible and move most of your logic and heavy lifting to classes under src. Then you can write unit tests for your classes and test them locally before pushing the changes.
I love the idea, and while it adds a few more steps, but the long term benefits are worth it.