JUnit Flashcards
What is JUnit?
JUnit is a unit testing framework for the Java application. It allows you to unit test your code at the method level. You can also use JUnit for test-driven development e.g. first writing test and then writing actual code. Most of the Java IDE like Eclipse, Netbeans and IntelliJ Idea provides out-of-box JUnit integration for TDD. Even build tools like Maven, Ant, and Gradle can run the JUnit test at compile and built time.
What is the difference between JUnit 3.X and JUnit 4.x?
The main difference between JUnit 3 and JUnit 4 is annotation. Earlier you need to start your method name as testXXX() but from JUnit 4.0 onwards you can use @Test annotation, which removes this dependency to start your Junit test methods as a test.
What do @Before and @After annotation does in JUnit 4?
@Before and @After annotation is used for setup and cleanup jobs. They are actually a replacement of the setUp() and tearDown() method of JUnit 3.X. Remember, a method annotated with @Before will be called before calling a test method and @After will be called after executing the test method.
So if you have 5 test methods in one JUnit test class, they will be called five times. You will be glad to know that JUnit 5 has renamed @Before to @After to @BeforeEach and @AfterEach to make it more readable.
What is the difference between @Before and @BeforeClass annotation in JUnit?
@Before is called per test method while @BeforeClass is called per-test-class level. Also, static methods are annotated with @BeforeClass and you can use them to initialize shared resources e.g. which should be shared by every instance of JUnit class like Database connection.
How does JUnit achieve the isolation of tests?
JUnit creates a separate instance of the test class for calling test methods. For example, if your test class contains 5 tets then JUnit will create 5 instances of the test class for executing those test methods. That’s why constructor is called before executing @Test methods. In JUnit 3.X, It used to first create instances and then call the methods but in JUnit 4.1, it first creates an instance and then calls them the method and then goes on to create the second method. This way, it keeps one test isolated from the other.
What is difference between setUp() and tearDown() method?
They are methods from JUnit 3.X which is replaced by @Before and @After annotated method. They are used for setting up resources before the test method and for doing clean-up after-test methods.
How do you check if a test method throws Exception in JUnit?
In JUnit 4, you can use @Test annotation with an expected parameter to specify the exception thrown by a test method. If the test method throws that Exception then JUnit will mark your test passed, otherwise, it will mark them as failed.
For example, if you want to verify your method should throw IllegalArgumentException if the given parameter is bad then you can annotate your test method as @Test(expected = IllegalArgumentException.class). In earlier versions e.g. on JUnit 3.X, you could have used catch block to verify if the method under test throws a particular exception or not.
How do you ignore certain test methods in the JUnit Test class?
Well, from JUnit 4 onwards you can use @Ignore annotation to instruct JUnit runtime to not execute any particular test or disable any test as shown in this JUnit ignore example. You can also use this method for annotating unimplemented test methods. Btw, you should use @Ignore only temporarily and remove it as soon as possible by either implementing the test methods or removing it if not required.
Can you test a Java method for timeout using JUnit?
Yes, JUnit provides a timeout parameter to @Test annotation which can be used to instruct JUnit to pass or fail a test method based upon execution time. For example, a JUnit test method annotated with @Test(timeout= 50) will be failed it doesn’t complete in 50 milliseconds (timeout is specified in millisecond). This is the standard way to verify the SLA of a Java method.
What are some best practices you follow while writing code to make it more testable?
Here are some of the best practices you can follow to make your code more testable :
1) Use interface instead of concrete class, this allows the tester to replace actual class with Mock or Stub for testing purpose.
2) Use Dependency injection, it makes it easy to test individual parts and supply dependency from test configuration. You can create an actual object which is dependent on the Mock and stub for testing. This also allows you to test a class even if its dependency is not yet coded.
3) Avoid static methods, they are difficult to test as they cannot be called polymorhpically.
What does @RunWith annotation do?
The @RunWith annotation allows you to run your JUnit test with another, custom JUnit Runner. For example, you can do some parameterized testing in JUnit by using @RunWith(Parameterized. class), this Runner is required for implementing parameterized tests in JUnit.
Some of the popular third-party implementations of JUnit runners include SpringJUnit4ClassRunner and MockitoJUnitRunner, which you can use with @RunWith annotation to test Spring beans and Mockito library.
how do you test a method which doesn’t return a value?
Well, you can test a method even if it doesn’t return a value by checking for its side effects, for example, add() method of ArrayList doesn’t return anything but it has a side effect of the increasing size of Collection by 1, so you can check whether add() is successful or not by checking the size() of List before and after calling this method as shown below:
What is the difference between Stub and Mock in Unit testing?
Though both Stub and Mock are tools for unit testing and used in place of actual class to facilitate unit testing there is some subtle difference between them. Mocks are generally more powerful becuase they can record method calls and there are also good frameworks like Mockito and PowerMock available, which can create Mock for you.
Stubs are easier to use but require more coding than Mocks becuase you need to create your own Stub implementation. Many Java developers prefer mocks over stubs becuase of this reason only.
What happens when your JUnit test method throws an exception?
When a JUnit method throws an uncaught exception, which is also not declared as expected using the @Test(expected) parameter then the JUnit test will fail, but if it’s declared and expected then the JUnit test will pass. If the method under test throws an exception that is caught by you inside the JUnit test method then nothing will happen and the test will be passed
How do you test protected Java methods using JUnit?
Since protected methods are accessible to everyone inside the same package they are declared, you can put your JUnit test class also on the same package to test them. But, don’t mix your test code with real code, instead, put them on a different source tree. You can use a Maven-like structure to organize your test and source classes in different folders.
Can you test a private method using JUnit?
Well, since private methods are not accessible outside the class they are declared, it’s not possible to test them using JUnit directly, but you can use Reflection to make them accessible by calling setAccessible(true) before testing. Another way to test private method is via public methods, which uses them. In general, testing the private method is also an indication that those methods should be moved into another class to promote reusability.
What are some Unit testing libraries you know other than JUnit for Java programs?
Java is very lucky to have many great unit testing libraries including JUnit. Here are a couple of the most popular ones:
Mockito which is a Mocking framework can be used with JUnit
PowerMock, similar to Mockito but also provide mocking of static methods.
TestNG similar to JUnit
Spock groovy-based unit testing framework for the Java application. Thanks to JUnit Runner, you can use the Spock testing framework with Java IDEs as well.
At a bare minimum, you should JUnit and Mockito for writing unit tests in Java.
Does JUnit support Parameterized tests, where tests can be executed multiple times with different parameter values?
Yes, JUnit supports parameterized tests by using a custom Runner called Parameterized and @Parameters annotation. You use this annotation to annotate the method which provides parametric values and run the Test class with @RunWith(Parameterized. class) runner. You can also use object arrays to inject values.
What does @Rule annotation do?
It allows you to create JUnit rules, which can be used to add or redefine the behavior of each test method in a test class. You can write your own rules using @Rule annotation.
What are text fixtures in unit testing?
The fixture is a set of objects of a fixed state that is used as a baseline for running tests. The objective of a test fixture is to make sure that there is a well known and fixed environment to run tests so that results can be repeated. It includes the following two methods −
setUp() method – it runs before every test is called.
tearDown() method – it runs after every test method is called.
What is the difference between JUnit 4 and JUnit 5?
The JUnit 5 is the latest version of JUnit also known as Jupiter. The minimum JDK for JUnit 4 was JDK 5, while JUnit 5 requires at least JDK 8. Also, the @Before, @BeforeClass, @After, and @AfterClass annotations are now more readable than the @BeforeEach, @BeforeAll, @AfterEach, and @AfterAll annotations.
What is Testing?
Testing is the process of checking the functionality of the application whether it is working as per requirements.
What is Unit Testing?
Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.
What are important features of JUnit?
It is an open source framework.
Provides Annotation to identify the test methods.
Provides Assertions for testing expected results.
Provides Test runners for running tests.
JUnit tests can be run automatically and they check their own results and provide immediate feedback.
JUnit tests can be organized into test suites containing test cases and even other test suites.
JUnit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.