Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
JUnit Interview Questions for Freshers
2.1.
1. What is JUnit and how does it work?
2.2.
2. Is it possible in Java to use graphics?
2.3.
3. What is the concept of a Graphics object?
2.4.
4. What does the Graphics Class Package require?
2.5.
5. What are the different types of graphics modes?
2.6.
6. What is Testing?
2.7.
7. What exactly is a Unit Test Case?
2.8.
8. Describe how to create a simple JUnit test case.
2.9.
9. What are parameterized tests?
2.10.
10. Mention the various exception handling mechanisms in JUnit?
2.11.
11. What does it mean in JUnit to ignore a test?
2.12.
12. Can you name a few helpful JUnit extensions?
2.13.
13. Explain whether a developer or a tester should use JUnit. Why do you test your code with JUnit?
2.14.
 14. What is the JUnitCore Class?
2.15.
15. Can you explain how to start JUnit from the command window?
3.
JUnit Interview Questions for Experienced
3.1.
16. What makes JUnit 3.X and JUnit 4.x different?
3.2.
17. In JUnit 4, what do the annotations @Before and @After do?
3.3.
18. What is the difference between the annotations @Before and @BeforeClass in JUnit?
3.4.
19. How does JUnit achieve test isolation?
3.5.
20. In JUnit, how can you see if a test method throws an exception?
3.6.
21. In the JUnit Test class, how do you ignore specific test methods?
3.7.
22. Is it possible to use JUnit to test a Java timeout method?
3.8.
23. What are some of the best practices you use to make your code more testable when you're writing it?
3.9.
24. What is the purpose of the @RunWith annotation?
3.10.
25. In unit testing, what is the difference between a Stub and a Mock?
3.11.
26. When a JUnit test method throws an exception, what happens?
3.12.
27. How do you use JUnit to test protected Java methods?
3.13.
28. What is the purpose of the @Rule annotation?
3.14.
29. In unit testing, what are text fixtures?
3.15.
30. What happens if the return type of a JUnit method is 'string'?
4.
Junit Mockito Interview Questions
4.1.
31. What is the difference between a mock and a spy in Mockito?
4.2.
32. How do you verify that a method was called in Mockito?
4.3.
33. What is the purpose of @Mock and @InjectMocks annotations in Mockito?
4.4.
34. Can you mock private methods using Mockito?
4.5.
35. How do you reset mocks in Mockito?
4.6.
36. How do you mock a void method in Mockito?
4.7.
37. What is the use of ArgumentCaptor in Mockito?
4.8.
38. How can you mock static methods in Mockito?
4.9.
39. . How do you mock exceptions using Mockito?
4.9.1.
Using when().thenThrow():
4.10.
40. How do you test the number of times a method is called using Mockito?
5.
JUnit MCQ
5.1.
41. Which of the following is true about JUnit testing?
5.2.
42. What is the purpose of the @Before annotation in JUnit?
5.3.
43. In JUnit, what does the @Test annotation indicate?
5.4.
44. How can you specify a timeout for a test method in JUnit?
5.5.
45. What is the correct way to check for an exception in JUnit?
5.6.
46. In JUnit, what does the @AfterClass annotation do?
5.7.
47. Which of the following frameworks can be integrated with JUnit for mocking?
5.8.
48. What is a test suite in JUnit?
5.9.
49. How do you assert that two arrays are equal in JUnit?
5.10.
50. Which version of JUnit introduced the @BeforeClass and @AfterClass annotations?
6.
Conclusion
Last Updated: Sep 18, 2024

JUnit Interview Questions

Introduction 

JUnit is a Java unit testing framework. JUnit is part of the xUnit family of unit testing frameworks, which originated with SUnit and has played an essential role in the development of test-driven development. JUnit is linked as a JAR at the compile time. 

In this article, we've covered 30 Junit Interview Questions to brush up on your Junit testing framework. 

Junit Interview Questions

The JUnit Interview Questions were created specifically to familiarise you with the types of questions you can encounter during your JUnit interview.  Good interviewers rarely plan to ask any specific topic during the interview; instead, inquiries usually begin with a basic concept of the subject and progress based on more discussion and your responses. 

Let’s now discuss some of the JUnit interview questions.
Also Read: Java OOPs Interview Questions

JUnit Interview Questions for Freshers

JUnit Interview Questions for Freshers

1. What is JUnit and how does it work?

JUnit is a Java-based open-source unit testing framework that is critical to establishing a TDD culture (Test Driven Development). The TDD culture places a strong emphasis on preparing test data in order to test a logic that will be applied when the testing is complete. JUnit improves software stability by detecting bugs in the code logic early in the  phase, before the software is released to production. This cuts down on the time it takes to troubleshoot any issues later on.
 

2. Is it possible in Java to use graphics?

The simplest method is to use java. awt. Canvas and java. Awt.
 

3. What is the concept of a Graphics object?

The Graphics object is used to create graphical images, and it represents a GDI+ drawing surface. When dealing with graphics, there are two steps: Creating a Graphics object is the first step. To draw lines and shapes, produce text, or display and edit pictures, use the Graphics object.
 

4. What does the Graphics Class Package require?

The awt (abstract windowing toolkit) package contains the Graphics class. This class holds information about the current graphics 'context.' The current drawing colour, typeface, and transformation information are all included in the context.
 

5. What are the different types of graphics modes?

Graphics mode is a computer display mode that uses pixels to create images. Most people nowadays use their computers in graphical mode rather than text mode or command line mode.

  • Graphic Devices.
  • Colouring of graphs.
  • Pointing Devices.
  • Digital Images.
  • Digital Images.
  • screen dump.
  • posterization.
  • text mode.

 

6. What is Testing?

Testing is the process of determining whether an application's functionality meets the criteria.
 

7. What exactly is a Unit Test Case?

A unit test case is a section of code that ensures that another section of code (method) behaves correctly. There must be at least two test cases for each requirement. One test is negative, and the other is positive.
 

8. Describe how to create a simple JUnit test case.

  • Determine a TestCase subclass.
  • Override the setup() function to initialise the object(s) under test.
  • Override the teardown() function to release the object(s) under test.

 

9. What are parameterized tests?

Parameterized tests allow developers to perform the same test with varied parameters.The same test is run repeatedly with varied values in a parameterized test. It benefits developers in saving time while running identical tests that only differ in their inputs and anticipated outcomes. One can create a test method that retrieves data from a data source using parameterized testing.
 

10. Mention the various exception handling mechanisms in JUnit?

In JUnit, there are several methods for handling exceptions.

  • Try catch idiom
  • With JUnit rule
  • With @Test annotation
  • With catch exception library
  • With customs annotation

 

11. What does it mean in JUnit to ignore a test?

  • You can use the @Ignore annotation when your code isn't ready and would fail if executed.
  • A test method with the annotation @Ignore will not be executed.
  • If it's annotated with @Ignore, it won't execute any of the test methods in the test class.

 

12. Can you name a few helpful JUnit extensions?

Extensions for JUnit include

  • Cactus
  • JWebUnit
  • XMLUnit
  • MockObject

 

13. Explain whether a developer or a tester should use JUnit. Why do you test your code with JUnit?

Developers are more likely to utilise JUnit to implement unit tests in JAVA. It's made for unit testing, which is more of a coding than a testing process. Many testers and QA engineers, on the other hand, use JUnit for unit testing.

  • JUnit is utilised because it automates testing and tests early.
  • JUnit tests can be compiled with the build, allowing for regression testing at the unit level.
  • It enables the reuse of test code.
  • When there is a transfer, JUnit tests act as a document for the unit tests.

 

 14. What is the JUnitCore Class?

JUnitCore is a built-in class in the JUnit package that is based on the Façade design pattern and is solely used to run definite test classes.
 

15. Can you explain how to start JUnit from the command window?

You must follow the steps below to run JUnit from the command window.

  • CLASSPATH must be set.
  • Invoke the runner with the following command: Javaorg.junit.runner.JUnitCore

JUnit Interview Questions for Experienced

16. What makes JUnit 3.X and JUnit 4.x different?

Annotation is the key distinction between JUnit 3 and JUnit 4. Previously, you had to start your method name with testXXX(), but starting with JUnit 4.0, you may use the @Test annotation, which eliminates the need to start your Junit test methods with a test.
 

17. In JUnit 4, what do the annotations @Before and @After do?

@Before

@BeforeClass

  • @Before is used on a per-test-method level
  • Before executing a test within the current Test class, this method is executed.
  • Typically, this method helps in initialising the resources needed for the action test to execute. 
  • Every time a test method is run, it is executed first.
  • @BeforeClass is used on a per-test-class level
  • The execution of this method occurs before the running of any test in the current Test Class. It just executes once.
  • used to setup database connectivity before running any test.
  • In contrast to @Before, this method needs to be declared static.

 

18. What is the difference between the annotations @Before and @BeforeClass in JUnit?

@Before is used on a per-test-method level, whereas @BeforeClass is used on a per-test-class level. Static methods are also annotated with @BeforeClass and can be used to initialise common resources, such as database connections, that should be shared by all instances of the JUnit class.
 

19. How does JUnit achieve test isolation?

For calling test methods, JUnit creates a separate instance of the test class. If your test class has five tets, for example, JUnit will generate five instances of the test class to execute the test methods. As a result, constructor is invoked before the @Test methods are executed. It used to build instances first and then call the methods in JUnit 3.X, but in JUnit 4.1, it first produces an instance, then calls the method, and then creates the second method. It maintains one test apart from the other in this way.
 

20. In JUnit, how can you see if a test method throws an exception?

To specify the exception thrown by a test method in JUnit 4, use the @Test annotation with an expected parameter. JUnit will record your tests as passed if the test function throws that Exception; otherwise, it will mark them as failed. You can annotate your test method like @Test(expected = IllegalArgumentException.class) if you want to check that your function should throw IllegalArgumentException if the given parameter is wrong. You might have used catch blocks in older versions of JUnit, such as JUnit 3.X, to check whether the method under test throws a specific exception or not.
 

21. In the JUnit Test class, how do you ignore specific test methods?

As seen in this JUnit ignore example, you may use the @Ignore annotation to tell the JUnit runtime not to execute or disable any test starting with JUnit 4. This method can also be used to annotate test methods that have yet to be implemented. By the way, you should only use @Ignore for a limited time and then remove it as soon as possible by either implementing the test methods or removing it if it is no longer needed.
 

22. Is it possible to use JUnit to test a Java timeout method?

Yes, the @Test annotation in JUnit has a timeout parameter that can be used to instruct JUnit whether to pass or fail a test method based on execution time. If a JUnit test method annotated with @Test(timeout= 50) does not complete in 50 milliseconds, it will fail (timeout is specified in millisecond). This is the most common approach to check a Java method's SLA.
 

23. What are some of the best practices you use to make your code more testable when you're writing it?

The following are some of the recommended techniques for making your code more testable:

1) Use an interface instead of a concrete class; this allows the tester to test with a Mock or Stub instead of the actual class.

2) Use dependency injection to test separate pieces and supply dependencies from the test configuration. For testing, you can create an actual object that is dependent on the Mock and stub. This also lets you test a class even if its dependencies haven't been coded yet.

3) Avoid static methods, which are difficult to test since they are not polymorphic.
 

24. What is the purpose of the @RunWith annotation?

You can use the @RunWith annotation to run your JUnit test with a different, custom JUnit Runner. For example, you can use @RunWith(Parameterized. class) to accomplish some parameterized testing in JUnit; this Runner is required for developing parameterized tests in JUnit. SpringJUnit4ClassRunner and MockitoJUnitRunner are two popular third-party JUnit runners that you can use with the @RunWith annotation to test Spring beans and the Mockito library.
 

25. In unit testing, what is the difference between a Stub and a Mock?

Though both Stub and Mock are unit testing tools that are used in place of actual classes to make unit testing easier, there are some small differences between them. Mocks are more powerful in general since they can record method calls, and there are also frameworks like Mockito and PowerMock that can create Mocks for you.
 

26. When a JUnit test method throws an exception, what happens?

The JUnit test will fail if a JUnit method throws an uncaught exception that is not declared as expected using the @Test(expected) parameter, but it will pass if it is stated and expected. Nothing will happen if the method under test throws an exception that you catch inside the JUnit test function, and the test will pass.
 

27. How do you use JUnit to test protected Java methods?

Because protected methods are accessible to everyone inside the same package where they are declared, you can test them with your JUnit test class. However, do not mix your test code with real code; instead, keep them separate in a separate source tree. You can organise your test and source classes in different directories using a Maven-like layout.
 

28. What is the purpose of the @Rule annotation?

It lets you build JUnit rules to add or change the behaviour of each test method in a test class. Using the @Rule annotation, you can create your own rules.
 

29. In unit testing, what are text fixtures?

In unit testing, a test fixture is used to provide a known and consistent environment in which the test may be run. For testing, a text fixture, mock objects, or loading specific data from the database could be set up. JUnit supports the annotations @Before and @BeforeClass for constructing text fixtures, as well as @After and @Afterclass for cleanup.
 

30. What happens if the return type of a JUnit method is 'string'?

The return type of JUnit test methods is 'void'. As a result, the execution will be failed.

Junit Mockito Interview Questions

31. What is the difference between a mock and a spy in Mockito?

In Mockito, a mock is a dummy object created to test the functionality of a class in isolation. It does not execute the actual code of the class. A spy, on the other hand, wraps a real object and allows partial mocking. With a spy, you can call real methods while still being able to mock specific behavior.

32. How do you verify that a method was called in Mockito?

In Mockito, the verify() method is used to check if a method was invoked. For example, verify(mockObject).methodName(); ensures that the method methodName() was called on the mock object mockObject.

33. What is the purpose of @Mock and @InjectMocks annotations in Mockito?

The @Mock annotation is used in Mockito to create mock objects for classes and interfaces. This allows you to simulate the behavior of dependent objects when testing a class in isolation. Mocking removes the need to rely on actual implementations, making tests faster and less dependent on external factors.

The @InjectMocks annotation is used to inject the mocks created using @Mock (or @Spy) into the class under test. It simplifies the process of dependency injection during testing by automatically injecting the mock instances into the fields of the class being tested.

34. Can you mock private methods using Mockito?

Mockito does not support mocking private methods directly because mocking private methods is generally considered bad practice as it breaks the concept of encapsulation. However, if you still need to mock private methods (perhaps for legacy code), you can use a library like PowerMock in combination with Mockito to achieve this.

PowerMock provides the ability to mock static, final, and private methods. Here's an example of mocking a private method using PowerMock:

public class MyClass {
   private String privateMethod() {
       return "real response";
   }
   public String publicMethod() {
       return privateMethod();
   }
}


To mock the private method:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
   @Test
   public void testPrivateMethod() throws Exception {
       MyClass myClass = PowerMockito.spy(new MyClass());
       PowerMockito.when(myClass, "privateMethod").thenReturn("mocked response");
       String result = myClass.publicMethod();
       assertEquals("mocked response", result);
   }
}


Here, PowerMock allows you to mock the private method privateMethod() so that it returns "mocked response" instead of calling the real method. However, using PowerMock is generally recommended only when absolutely necessary.

35. How do you reset mocks in Mockito?

In Mockito, you can reset mocks using the reset() method. Resetting a mock clears all interactions, verifications, and stubbing that have been applied to it. This can be useful when you want to reuse the same mock object in different test cases but with fresh interactions and behavior.

Example:

Here's how you can reset a mock in Mockito:

@Test
public void testResetMock() {
   // Create a mock object
   MyService mockService = mock(MyService.class);
   // Stub a method
   when(mockService.someMethod()).thenReturn("Initial Call");
   // Call the method and verify behavior
   System.out.println(mockService.someMethod());  // Output: "Initial Call"
   verify(mockService).someMethod();
   // Reset the mock
   reset(mockService);
   // Now the mock has no previous interactions or stubbing
   System.out.println(mockService.someMethod());  // Output: null (default behavior)
   // Verify that no interactions have occurred after reset
   verify(mockService, times(0)).someMethod();
}


In this example:

  • We first stub mockService.someMethod() to return "Initial Call".
     
  • After calling reset(mockService), the mock is cleared of all interactions and stubbing.
     
  • Calling someMethod() after reset will return null, as no behavior is stubbed post-reset.

36. How do you mock a void method in Mockito?

To mock a void method, you can use doNothing() or doThrow() along with when(). For example:

doNothing().when(mockObject).voidMethod();

 

This mocks the behavior of the voidMethod() and ensures it does nothing when called.

37. What is the use of ArgumentCaptor in Mockito?

ArgumentCaptor is used to capture arguments passed to mock methods. It allows you to capture the arguments passed during method invocation and verify or assert them in your tests.

38. How can you mock static methods in Mockito?

Mockito does not directly support mocking static methods, but with Mockito 3.4 and above, static methods can be mocked using the mockStatic() method. Alternatively, libraries like PowerMock can also be used for this purpose.

39. . How do you mock exceptions using Mockito?

n Mockito, you can mock exceptions using either doThrow() or when().thenThrow(). These methods allow you to simulate exception behavior for methods in your tests, making it easier to test how your code handles exceptional situations.

Using when().thenThrow():

This approach is commonly used to mock exceptions when a method is called.
Using doThrow():

doThrow() is useful when mocking methods that return void.

40. How do you test the number of times a method is called using Mockito?

You can use Mockito’s verify() method along with the times() parameter to check how many times a particular method has been invoked during the test. This is useful when you want to ensure that a method is called a specific number of times during execution.

Example:

Here's an example of verifying that a method is called a certain number of times:

@Test
public void testMethodCallCount() {
   // Create a mock object
   MyService mockService = mock(MyService.class);
   // Call the method twice
   mockService.someMethod();
   mockService.someMethod();
   // Verify the method was called exactly two times
   verify(mockService, times(2)).someMethod();
}

In this example:

  • mockService.someMethod() is called twice.
  • verify(mockService, times(2)).someMethod(); checks whether someMethod() was called exactly two times.

JUnit MCQ

41. Which of the following is true about JUnit testing?

  • A) JUnit is used for unit testing.
  • B) JUnit can test both Java classes and interfaces.
  • C) JUnit is a framework for integration testing.
  • D) JUnit cannot be used with mocking frameworks.

Answer: A) JUnit is used for unit testing.

42. What is the purpose of the @Before annotation in JUnit?

  • A) It runs a method before each test.
  • B) It runs a method before all tests.
  • C) It runs a method after each test.
  • D) It runs a method after all tests.

Answer: A) It runs a method before each test.

43. In JUnit, what does the @Test annotation indicate?

  • A) A class is under test.
  • B) A method is a test method.
  • C) A method should be ignored.
  • D) A method is private.

Answer: B) A method is a test method.

44. How can you specify a timeout for a test method in JUnit?

  • A) Using the @Timeout annotation.
  • B) Using the @Test(timeout=1000) annotation.
  • C) Using the @Timeout(1000) annotation.
  • D) Using the @Before annotation.

Answer: B) Using the @Test(timeout=1000) annotation.

45. What is the correct way to check for an exception in JUnit?

  • A) @Test(expected=Exception.class)
  • B) @Expect(Exception.class)
  • C) @Throw(Exception.class)
  • D) @Before(Exception.class)

Answer: A) @Test(expected=Exception.class)

46. In JUnit, what does the @AfterClass annotation do?

  • A) It runs a method after each test.
  • B) It runs a method after all tests in the class.
  • C) It runs a method before each test.
  • D) It runs a method before all tests in the class.

Answer: B) It runs a method after all tests in the class.

47. Which of the following frameworks can be integrated with JUnit for mocking?

  • A) Mockito
  • B) PowerMock
  • C) EasyMock
  • D) All of the above

Answer: D) All of the above

48. What is a test suite in JUnit?

  • A) A single test case.
  • B) A group of test cases.
  • C) A method for running a single test.
  • D) A way to skip tests.

Answer: B) A group of test cases.

49. How do you assert that two arrays are equal in JUnit?

  • A) assertEquals(array1, array2)
  • B) assertArrayEquals(array1, array2)
  • C) assertEqualArrays(array1, array2)
  • D) assertEqualsArray(array1, array2)

Answer: B) assertArrayEquals(array1, array2)

50. Which version of JUnit introduced the @BeforeClass and @AfterClass annotations?

  • A) JUnit 3
  • B) JUnit 4
  • C) JUnit 5
  • D) None of the above

Answer: B) JUnit 4

Conclusion

In this article, we have extensively discussed the JUnit interview questions, the testing framework, and its implementation in unit testing using Java programming. We hope these JUnit interview questions have helped you enhance your knowledge regarding the preparation of questions for mocking and unit testing in Java. 

If you would like to learn more, check out our articles on  JUnit Introduction and FeaturesJUnit Environment Setup and Frameworkjunit-jupitermockito-integration-in-junitBasics of Java and many more. 

Recommended Reading:

Refer to our guided paths on Code360. to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning!

Live masterclass