To automate unit testing using Jenkins, where every code push to a Git repository triggers a pipeline that runs unit tests (e.g., JUnit for Java or PyTest for Python). This ensures code quality before deployment.
http://<JENKINS_SERVER>:8080/github-webhook/
pipeline {
agent any
stages {
stage('Checkout Code') {
steps {
git branch: 'main', url: 'https://github.com/your-repo.git'
}
}
stage('Build Project') {
steps {
sh 'mvn clean install'
}
}
stage('Run Unit Tests') {
steps {
sh 'mvn test'
}
post {
always {
junit '**/target/surefire-reports/*.xml'
}
}
}
}
post {
success {
echo "Tests passed!"
}
failure {
echo "Tests failed!"
}
}
}
pipeline {
agent any
stages {
stage('Checkout Code') {
steps {
git branch: 'main', url: 'https://github.com/your-repo.git'
}
}
stage('Setup Environment') {
steps {
sh 'python3 -m venv venv && source venv/bin/activate'
sh 'pip install -r requirements.txt'
}
}
stage('Run Unit Tests') {
steps {
sh 'pytest --junitxml=pytest_results.xml'
}
post {
always {
junit '**/pytest_results.xml'
}
}
}
}
post {
success {
echo "Tests passed!"
}
failure {
echo "Tests failed!"
}
}
}
Jenkinsfile:
post {
success {
slackSend channel: '#ci-cd', message: "Build Passed: ${env.BUILD_URL}"
}
failure {
slackSend channel: '#ci-cd', message: "Build Failed: ${env.BUILD_URL}"
}
}
This setup ensures a robust CI/CD pipeline with automated testing, improving software quality and development speed.