March 20, 2020
Estimated Post Reading Time ~

Introduction on JUNIT code coverage

1. Overview
What is Unit Testing?
JUnit is an open-source Unit Testing Framework for JAVA. It is useful for Java Developers to write and run repeatable tests. Erich Gamma and Kent Beck initially develop it. It is an instance of xUnit architecture. As the name implies, it is used for Unit Testing of a small chunk of code.
Developers who are following test-driven methodology must write and execute unit test first before any code.
Once you are done with code, you should execute all tests, and it should pass. Every time any code is added, you need to re-execute all test cases and makes sure nothing is broken.
Unit testing simply verifies that individual units of code (mostly functions) work independently as expected. Usually, you write the test cases yourself to cover the code you wrote. Unit tests verify that the component you wrote works fine when we ran it independently.
A unit test is a piece of code written by a developer that executes a specific functionality in the code to be tested and asserts a certain behavior or state.
The percentage of code which is tested by unit tests is typically called test coverage.
A unit test targets a small unit of code, e.g., a method or a class. External dependencies should be removed from unit tests, e.g., by replacing the dependency with a test implementation or a (mock) object created by a test framework.
Unit tests are not suitable for testing complex user interface or component interaction. For this, you should develop integration tests.
Unit testing is an idea to test project unit by unit, part by part.
Debugging isn't part of unit testing but part of testing step by step.
Unit tests ideally should cover all corner cases plus some random inputs for each project's unit to check whether it works properly.
JUnit allows to assure that methods return expected results and throw expected exceptions. It's is integrated with Eclipse to make the whole testing process a bit easier.  Assert() methods throw an exception marking given test as 'failed' when the result of the tested method is different than expected.

Why you need JUnit testing
·       It finds bugs early in the code, which makes our code more reliable.
·       JUnit is useful for developers, who work in a test-driven environment.
·       Unit testing forces a developer to read code more than writing.
·       You develop more readable, reliable and bug-free code which builds confidence during development.
Advantages of JUnit
·       All the old assert statements are same as before.
·       Most of the things are easier in JUnit4 as..With JUnit 4 you are more capable of identifying exception. You can define expected exception as a parameter while using @test annotation.Parameterized test is introduced, which enables us to use parameters.JUnit4 still can execute JUnit3 tests.
·       JUnit 4 can be used with java5 or higher version.
·       While using JUnit4, you are not required to extend JUnit.framework.TestCase. You can just create a simple java class.
·       You need to use annotations in spite of special method name as before.Instead of using setup method, you need to use @before annotation.Instead of using teardown method, put @after annotation.Instead of using testxxxx before method name, use @test annotation.
1.1. What is JUnit 5?
Unlike previous versions of JUnit, JUnit 5 is composed of several different modules from three different sub-projects.
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
The JUnit Platform serves as a foundation for launching testing frameworks on the JVM. It also defines the TestEngine API for developing a testing framework that runs on the platform. Furthermore, the platform provides a Console Launcher to launch the platform from the command line and a JUnit 4 based Runner for running any TestEngine on the platform in a JUnit 4 based environment. First-class support for the JUnit Platform also exists in popular IDEs (see IntelliJ IDEAEclipseNetBeans, and Visual Studio Code) and build tools (see GradleMaven, and Ant).
JUnit Jupiter is the combination of the new programming model and extension model for writing tests and extensions in JUnit 5. The Jupiter sub-project provides a TestEngine for running Jupiter based tests on the platform.
JUnit Vintage provides a TestEngine for running JUnit 3 and JUnit 4 based tests on the platform.
1.2. Supported Java Versions
JUnit 5 requires Java 8 (or higher) at runtime. However, you can still test code that has been compiled with previous versions of the JDK.
1.3. Getting Help
Ask JUnit 5 related questions on Stack Overflow or chat with us on Gitter.
1.4. Getting Started
1.4.1. Downloading JUnit Artifacts
To find out what artifacts are available for download and inclusion in your project, refer to Dependency Metadata. To set up dependency management for your build, refer to Build Support and the Example Projects.
1.4.2. JUnit 5 Features
To find out what features are available in JUnit 5 and how to use them, read the corresponding sections of this User Guide, organized by topic.
·       Running Tests
·       Advanced Topics
1.4.3. Example Projects
To see complete, working examples of projects that you can copy and experiment with, the junit5-samples repository is a good place to start. The junit5-samples repository hosts a collection of sample projects based on JUnit Jupiter, JUnit Vintage, and other testing frameworks. You’ll find appropriate build scripts (e.g., build.gradlepom.xml, etc.) in the example projects. The links below highlight some of the combinations you can choose from.
·       For Gradle and Java, check out the junit5-jupiter-starter-gradle project.
·       For Gradle and Kotlin, check out the junit5-jupiter-starter-gradle-kotlin project.
·       For Gradle and Groovy, check out the junit5-jupiter-starter-gradle-groovy project.
·       For Maven, check out the junit5-jupiter-starter-maven project.
·       For Ant, check out the junit5-jupiter-starter-ant project.
2. Writing Tests
The following example provides a glimpse at the minimum requirements for writing a test in JUnit Jupiter. Subsequent sections of this chapter will provide further details on all available features.
A first test case
import static org.junit.jupiter.api.Assertions.assertEquals;
import example.util.Calculator;
import org.junit.jupiter.api.Test;

class MyFirstJUnitJupiterTests {
    private final Calculator calculator = new Calculator();

    @Test
    void addition() {
        assertEquals(2, calculator.add(11));
    }
}
2.1. Annotations
JUnit Jupiter supports the following annotations for configuring tests and extending the framework.
Unless otherwise stated, all core annotations are located in the org.junit.jupiter.api package in the junit-jupiter-api module.

Annotation
Description
@Test
Denotes that a method is a test method. Unlike JUnit 4’s @Test 
annotation, this annotation does not declare any attributes, since
 test extensions in JUnit Jupiter operate based on their own 
dedicated annotations. Such methods are inherited unless they 
are overridden.
@ParameterizedTest
Denotes that a method is a parameterized test. Such methods 
are inherited unless they are overridden.
@RepeatedTest
Denotes that a method is a test template for a repeated test
Such methods are inherited unless they are overridden.
@TestFactory
Denotes that a method is a test factory for dynamic tests
Such methods are inherited unless they are overridden.
@TestTemplate
Denotes that a method is a template for test cases designed to 
be invoked multiple times depending on the number of invocation
 contexts returned by the registered providers. Such methods 
are inherited unless they are overridden.
@TestMethodOrder
Used to configure the test method execution order for the 
annotated test class; similar to JUnit 4’s @FixMethodOrder
Such annotations are inherited.
@TestInstance
Used to configure the test instance lifecycle for the annotated 
test class. Such annotations are inherited.
@DisplayName
Declares a custom display name for the test class or test method.
 Such annotations are not inherited.
@DisplayNameGeneration
Declares a custom display name generator for the test class. 
Such annotations are inherited.
@BeforeEach
Denotes that the annotated method should be executed before each @Test@RepeatedTest@ParameterizedTest,
 or @TestFactory method in the current class; analogous to JUnit 4’s 
@Before. Such methods are inherited unless they are overridden.
@AfterEach
Denotes that the annotated method should be executed after each @Test@RepeatedTest@ParameterizedTest
or @TestFactory method in the current class; analogous to JUnit 4’s 
@After. Such methods are inherited unless they are overridden.
@BeforeAll
Denotes that the annotated method should be executed before all @Test@RepeatedTest@ParameterizedTest
and @TestFactory methods in the current class; analogous to JUnit 
4’s @BeforeClass. Such methods are inherited (unless they are hidden 
or overridden) and must be static (unless the "per-class" 
@AfterAll
Denotes that the annotated method should be executed after all @Test@RepeatedTest@ParameterizedTest
and @TestFactory methods in the current class; analogous to J
Unit 4’s @AfterClass. Such methods are inherited (unless they are 
hidden or overridden) and must be static (unless the "per-class"
@Nested
Denotes that the annotated class is a non-static nested test class@BeforeAll and @AfterAll methods cannot be used directly in 
@Nested test class unless the "per-class" test instance lifecycle is 
used. Such annotations are not inherited.
@Tag
Used to declare tags for filtering tests, either at the class or method 
level; analogous to test groups in TestNG or Categories in JUnit 4. 
Such annotations are inherited at the class level but not at the method level.
@Disabled
Used to disable a test class or test method; analogous to JUnit 4’s 
@Ignore. Such annotations are not inherited.
@Timeout
Used to fail a test, test factory, test template, or lifecycle method if 
its execution exceeds a given duration. Such annotations are inherited.
@ExtendWith
Used to register extensions declaratively. Such annotations are inherited.
@RegisterExtension
Used to register extensions programmatically via fields. Such fields are 
inherited unless they are shadowed.
@TempDir
Used to supply a temporary directory via field injection or parameter 
injection in a lifecycle method or test method; located in the 
org.junit.jupiter.api.io package.
Some annotations may currently be experimental. Consult the table in Experimental APIs for
details.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.