JUnit Flashcards

1
Q

What is JUnit?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between JUnit 3.X and JUnit 4.x?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What do @Before and @After annotation does in JUnit 4?

A

@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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between @Before and @BeforeClass annotation in JUnit?

A

@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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does JUnit achieve the isolation of tests?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is difference between setUp() and tearDown() method?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you check if a test method throws Exception in JUnit?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you ignore certain test methods in the JUnit Test class?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Can you test a Java method for timeout using JUnit?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are some best practices you follow while writing code to make it more testable?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does @RunWith annotation do?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

how do you test a method which doesn’t return a value?

A

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:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between Stub and Mock in Unit testing?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What happens when your JUnit test method throws an exception?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you test protected Java methods using JUnit?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Can you test a private method using JUnit?

A

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.

17
Q

What are some Unit testing libraries you know other than JUnit for Java programs?

A

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.

18
Q

Does JUnit support Parameterized tests, where tests can be executed multiple times with different parameter values?

A
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.
19
Q

What does @Rule annotation do?

A

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.

20
Q

What are text fixtures in unit testing?

A

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.

21
Q

What is the difference between JUnit 4 and JUnit 5?

A

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.

22
Q

What is Testing?

A

Testing is the process of checking the functionality of the application whether it is working as per requirements.

23
Q

What is Unit Testing?

A

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.

24
Q

What are important features of JUnit?

A

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.

25
Q

Why does JUnit only report the first failure in a single test?

A

Reporting multiple failures in a single test is generally a sign that the test does too much and it is too big a unit test. JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test.

26
Q

In Java, assert is a keyword. Won’t this conflict with JUnit’sassert() method?

A

JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works exactly the same way. JUnit 4 is compatible with the assert keyword. If you run with the -ea JVM switch, assertions that fail will be reported by JUnit

27
Q

What is @Before and @BeforeClass and it’s usage?

A

@Before annotation:

syntax:
@Before
public void myMethod()

This method should execute before each test. Such methods are generally used for initialization before performing a actual test in test environment.

@BeforeClass annotation:

syntax:
@BeforeClass
public static void myMethod()

This method should execute before all the tests. It executes only once. Method should be declared static. Mostly used for database connectivity tasks before execution of any of the test.

28
Q

How @Test annotation is used for testing exceptions?

A

@Test (expected = Exception.class)

Limitation: It is used for testing only a single exception.

29
Q

What are the top advantages of writing unit tests?

A

The advantages of writing unit tests include Design testability, Code testability and Code maintainability as good unit tests enforces Object Oriented principles such as Single Responsibility etc. which enables people to avoid code smells such as long classes, long methods, large conditionals etc.

30
Q

Name some code smells which makes it hard to achieve high code coverage?

A

Long method, Large conditionals

31
Q

What are the different methods of exception handling in JUnit?

A
There are different ways of exception handling in JUnit. Try catch idiom.
Using JUnit rule.
@Test annotation.
Using catch exception library.
Using customs annotation.
32
Q

If the JUnit method’s return type is ‘string’, what will happen?

A

JUnit test methods are designed to return ‘void’. So the execution will fail.