fbpx

Top 100 JUnit Interview Questions and Answers

Top 100 Junit Interview Questions and Answers

Contents show

1. What is JUnit?

JUnit is a popular open-source testing framework for Java. It provides annotations to identify test methods and assertions to validate expected outcomes.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class MyTest {

    @Test
    public void testAddition() {
        int result = Calculator.add(3, 4);
        assertEquals(7, result);
    }
}

Official Reference


2. How do you install JUnit?

Add the JUnit dependency in your pom.xml file for Maven projects. For Gradle, add the dependency in the build.gradle file.

Example (Maven):

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

Official Reference


3. Explain the @Test annotation.

@Test is an annotation used to mark a method as a test method. JUnit will identify and execute methods annotated with @Test.

Example:

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class MyTest {

    @Test
    public void testIsPositive() {
        assertTrue(Calculator.isPositive(5));
    }
}

Official Reference


4. What is an Assertion in JUnit?

An assertion is a statement that checks whether a condition is true. If the condition is false, it throws an error.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class MyTest {

    @Test
    public void testDivision() {
        int result = Calculator.divide(10, 2);
        assertEquals(5, result);
    }
}

Official Reference


5. How do you perform parameterized testing in JUnit?

Use the @Parameterized annotation along with @ValueSource or @MethodSource to run the same test with different inputs.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

public class MyTest {

    @ParameterizedTest
    @ValueSource(ints = {1, 2, 3, 4, 5})
    public void testIsPositive(int number) {
        assertEquals(true, Calculator.isPositive(number));
    }
}

Official Reference


6. How do you handle exceptions in JUnit tests?

Use the @Test annotation with expected attribute or use assertThrows from JUnit 4.7 onwards.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class MyTest {

    @Test(expected = ArithmeticException.class)
    public void testDivisionByZero() {
        int result = Calculator.divide(10, 0);
    }
}

Official Reference


7. What is the purpose of @Before and @After annotations?

@Before and @After annotations are used to run setup and cleanup code before and after each test method.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.After;

public class MyTest {

    @Before
    public void setUp() {
        // Initialization code
    }

    @Test
    public void testAddition() {
        int result = Calculator.add(3, 4);
        assertEquals(7, result);
    }

    @After
    public void tearDown() {
        // Cleanup code
    }
}

Official Reference


8. Explain the purpose of @BeforeClass and @AfterClass annotations.

These annotations are used for setup and cleanup tasks that need to be performed once before and after all test methods in a test class.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.AfterClass;

public class MyTest {

    @BeforeClass
    public static void setUpClass() {
        // One-time initialization code
    }

    @Test
    public void testAddition() {
        int result = Calculator.add(3, 4);
        assertEquals(7, result);
    }

    @AfterClass
    public static void tearDownClass() {
        // One-time cleanup code
    }
}

Official Reference


9. What is the purpose of @Ignore annotation?

@Ignore is used to temporarily disable a test case.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;

public class MyTest {

    @Ignore
    @Test
    public void testThisIsIgnored() {
        // Test code that should be ignored
    }

    @Test
    public void testThisIsExecuted() {
        int result = Calculator.add(3, 4);
        assertEquals(7, result);
    }
}

Official Reference


10. What is a Test Suite in JUnit?

A Test Suite is a container that allows you to run multiple test cases together.

Example:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    TestClass1.class,
    TestClass2.class,
    TestClass3.class
})
public class TestSuite {
    // This class remains empty
}

Official Reference


11. How do you use JUnit with Maven?

Add the JUnit dependency in the pom.xml file under the <dependencies> section.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

Official Reference


12. What is the purpose of @RunWith annotation?

@RunWith is used to specify a custom test runner. For example, @RunWith(Parameterized.class) is used for parameterized tests.

Example:

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class MyParameterizedTest {
    // ...
}

Official Reference


13. How do you assert exceptions in JUnit 4?

Use @Test with expected attribute or use assertThrows() method from JUnit 4.7 onwards.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class MyTest {

    @Test(expected = ArithmeticException.class)
    public void testDivisionByZero() {
        int result = Calculator.divide(10, 0);
    }
}

Official Reference


14. What is the purpose of @Rule annotation?

@Rule is used to define additional behavior for a test method. For example, TemporaryFolder creates temporary folders for tests.

Example:

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class MyTest {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void testFileCreation() throws IOException {
        File createdFile = folder.newFile("test.txt");
        assertTrue(createdFile.exists());
    }
}

Official Reference


15. What is the purpose of @ClassRule annotation?

@ClassRule is similar to @Rule, but it applies to all the test methods in a class.

Example:

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class MyTest {

    @ClassRule
    public static TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void testFileCreation() throws IOException {
        File createdFile = folder.newFile("test.txt");
        assertTrue(createdFile.exists());
    }
}

Official Reference


16. What is the purpose of @Category annotation?

@Category allows you to categorize your tests and run only a specific category of tests.

Example:

import org.junit.Test;
import org.junit.experimental.categories.Category;

public class MyTest {

    @Category(FastTests.class)
    @Test
    public void testFastOperation() {
        // Test code
    }

    @Category(SlowTests.class)
    @Test
    public void testSlowOperation() {
        // Test code
    }
}

Official Reference


17. What is Mockito in JUnit?

Mockito is a mocking framework that allows you to create and configure mock objects. It’s often used to test code in isolation.

Example:

import static org.mockito.Mockito.*;

List<String> mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("Hello");

assertEquals("Hello", mockedList.get(0));

Official Reference


18. What is the purpose of @Mock annotation in Mockito?

@Mock is used to create a mock object. It simplifies the process of creating mock objects.

Example:

@Mock
List<String> mockedList;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    when(mockedList.get(0)).thenReturn("Hello");
}

@Test
public void testMockedList() {
    assertEquals("Hello", mockedList.get(0));
}

Official Reference


19. What is a Matcher in Mockito?

Matchers are used in Mockito to define the behavior of mock objects.

Example:

import static org.mockito.Mockito.*;

List<String> mockedList = mock(List.class);
when(mockedList.get(anyInt())).thenReturn("Hello");

assertEquals("Hello", mockedList.get(0));

Official Reference


20. How do you verify method calls in Mockito?

Use verify() to check if a method is called with specific arguments.

Example:

import static org.mockito.Mockito.*;

List<String> mockedList = mock(List.class);
mockedList.add("Hello");

verify(mockedList).add("Hello");

Official Reference


21. What is a Spy in Mockito?

A spy in Mockito is a partial mock. It allows you to wrap a real object and selectively mock some of its methods.

Example:

List<String> list = new LinkedList<>();
List<String> spyList = spy(list);

doReturn("Hello").when(spyList).get(0);

Official Reference


22. How do you mock void methods in Mockito?

Use doNothing(), doThrow(), doReturn() with when() to mock void methods.

Example:

List<String> mockedList = mock(List.class);
doNothing().when(mockedList).clear();

Official Reference


23. What is the purpose of ArgumentCaptor in Mockito?

ArgumentCaptor is used to capture arguments passed to mock objects.

Example:

List<String> mockedList = mock(List.class);
mockedList.add("Hello");

ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
verify(mockedList).add(argument.capture());

assertEquals("Hello", argument.getValue());

Official Reference


24. What is the purpose of @RunWith(MockitoJUnitRunner.class)?

@RunWith(MockitoJUnitRunner.class) is used to automatically initialize annotated mocks and spies.

Example:

@RunWith(MockitoJUnitRunner.class)
public class MyTest {
    @Mock
    List<String> mockedList;

    @Test
    public void testMockedList() {
        when(mockedList.get(0)).thenReturn("Hello");
        assertEquals("Hello", mockedList.get(0));
    }
}

Official Reference


25. What is the purpose of MockitoAnnotations.initMocks(this)?

MockitoAnnotations.initMocks(this) is used to initialize annotated mocks and spies manually.

Example:

public class MyTest {

    @Mock
    List<String> mockedList;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testMockedList() {
        when(mockedList.get(0)).thenReturn("Hello");
        assertEquals("Hello", mockedList.get(0));
    }
}

Official Reference


26. What is a MockSettings in Mockito?

MockSettings allow you to configure additional behaviors for a mock.

Example:

List<String> mockedList = mock(List.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));

String result = mockedList.get(0); // Returns a SmartNull

Official Reference


27. What is the purpose of RETURNS_SMART_NULLS in Mockito?

RETURNS_SMART_NULLS is a MockSettings that returns a SmartNull for unstubbed invocations.

Example:

List<String> mockedList = mock(List.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));

String result = mockedList.get(0); // Returns a SmartNull

Official Reference


28. What is a MockMaker in Mockito?

MockMaker is a strategy interface that determines how mocks are created.

Example: (Not directly used in test code)

Official Reference


29. What is the purpose of @MockBean in Spring Boot?

@MockBean is used in Spring Boot to mock beans when testing.

Example:

@SpringBootTest
public class MyServiceTest {

    @Autowired
    private MyService service;

    @MockBean
    private ExternalDependency dependency;

    @Test
    public void testServiceMethod() {
        when(dependency.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.getDataFromDependency());
    }
}

Official Reference


30. What is the purpose of @SpyBean in Spring Boot?

@SpyBean is used in Spring Boot to create a partial mock of a bean.

Example:

@SpringBootTest
public class MyServiceTest {

    @Autowired
    private MyService service;

    @SpyBean
    private ExternalDependency dependency;

    @Test
    public void testServiceMethod() {
        when(dependency.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.getDataFromDependency());
    }
}

Official Reference


31. What is the purpose of @InjectMocks in Mockito?

@InjectMocks is used in Mockito to inject mocks into the class under test.

Example:

public class MyService {

    @Autowired
    private ExternalDependency dependency;

    public String processData() {
        String data = dependency.getData();
        // Process data
        return data;
    }
}

@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {

    @Mock
    private ExternalDependency dependency;

    @InjectMocks
    private MyService service;

    @Test
    public void testProcessData() {
        when(dependency.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.processData());
    }
}

Official Reference


32. What is a TestDouble?

A TestDouble is a general term for any kind of pretend object used in place of a real object for testing purposes.

Example: Mocks, stubs, fakes, etc.

Official Reference


33. What is a Stub in Mockito?

A Stub in Mockito is an object that provides predefined answers to method calls.

Example:

List<String> mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("Hello");

assertEquals("Hello", mockedList.get(0));

Official Reference


34. What is a Mock vs. a Stub?

A Mock is an object with the ability to record method calls and their parameters. A Stub, on the other hand, provides predefined answers to method calls.

Example:

// Mock
List<String> mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("Hello");

// Stub
List<String> stubList = mock(List.class);
when(stubList.get(0)).thenReturn("Hello");

Official Reference


35. What is a Fake in Mockito?

A Fake is a simplified implementation of a class, often used in place of the real implementation for testing.

Example:

public class FakeDatabase implements Database {
    // Simplified implementation for testing
}

Official Reference


36. What is a Spy vs. a Mock?

A Spy in Mockito is a partial mock that wraps a real object. It allows you to selectively mock some methods. A Mock, on the other hand, is a complete mock of a class or interface.

Example:

// Spy
List<String> spyList = spy(new ArrayList<>());
doReturn("Hello").when(spyList).get(0);

// Mock
List<String> mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("Hello");

Official Reference


37. What is a Captor in Mockito?

A Captor is used to capture arguments passed to a mock object for further verification.

Example:

List<String> mockedList = mock(List.class);
mockedList.add("Hello");

ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
verify(mockedList).add(argument.capture());

assertEquals("Hello", argument.getValue());

Official Reference


38. How do you mock static methods in Mockito?

You can use the PowerMock extension in combination with Mockito to mock static methods.

Example:

@PrepareForTest(MyClassWithStaticMethod.class)
public class MyTest {

    @Test
    public void testMethodWithStaticCall() {
        PowerMockito.mockStatic(MyClassWithStaticMethod.class);
        when(MyClassWithStaticMethod.staticMethod()).thenReturn("Mocked Value");

        assertEquals("Mocked Value", MyClassWithStaticMethod.staticMethod());
    }
}

Official Reference


39. How do you mock private methods in Mockito?

You can use the PowerMock extension in combination with Mockito to mock private methods.

Example:

@PrepareForTest(MyClassWithPrivateMethod.class)
public class MyTest {

    @Test
    public void testMethodWithPrivateCall() throws Exception {
        PowerMockito.spy(MyClassWithPrivateMethod.class);
        PowerMockito.when(MyClassWithPrivateMethod.class, "privateMethod").thenReturn("Mocked Value");

        MyClassWithPrivateMethod instance = new MyClassWithPrivateMethod();
        String result = instance.methodCallingPrivateMethod();

        assertEquals("Mocked Value", result);
    }
}

Official Reference


40. What is a Mocking Framework?

A mocking framework is a tool or library that simplifies the process of creating mock objects for testing.

Example: Mockito, PowerMock, EasyMock, etc.

Official Reference


41. What is the purpose of @SpringBootTest in Spring Boot?

@SpringBootTest is used in Spring Boot to load the entire application context for integration testing.

Example:

@SpringBootTest
public class MyIntegrationTest {

    @Autowired
    private MyService service;

    @Test
    public void testServiceMethod() {
        String result = service.getData();
        assertEquals("Expected Result", result);
    }
}

Official Reference


42. How do you use TestNG with Mockito?

You can use the @Mock annotation from Mockito along with @BeforeMethod or @BeforeClass from TestNG to initialize mocks.

Example:

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class MyTest {

    @Mock
    private MyService service;

    @BeforeMethod
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testServiceMethod() {
        when(service.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.getData());
    }
}

Official Reference


43. How do you use JUnit 5 with Mockito?

JUnit 5 provides the @ExtendWith(MockitoExtension.class) annotation to use Mockito with JUnit 5.

Example:

@ExtendWith(MockitoExtension.class)
public class MyTest {

    @Mock
    private MyService service;

    @Test
    public void testServiceMethod() {
        when(service.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.getData());
    }
}

Official Reference


44. What is the purpose of @WebMvcTest in Spring Boot?

@WebMvcTest is used in Spring Boot to focus only on the web layer and load only the relevant components for testing controllers.

Example:

@WebMvcTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyService service;

    @Test
    public void testController() throws Exception {
        when(service.getData()).thenReturn("Mocked Data");

        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(content().string("Mocked Data"));
    }
}

Official Reference


45. How do you use JUnit 4 and JUnit 5 in the same project?

You can use both JUnit 4 and JUnit 5 in the same project by including their dependencies and annotations accordingly.

Example:

<!-- JUnit 4 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

<!-- JUnit 5 -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.7.2</version>
    <scope>test</scope>
</dependency>

Official Reference


46. How do you use AssertJ with JUnit?

Add the AssertJ dependency in your pom.xml file for Maven projects.

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.21.0</version>
    <scope>test</scope>
</dependency>

Then, you can use AssertJ assertions in your tests.

Example:

import static org.assertj.core.api.Assertions.assertThat;

@Test
public void testAddition() {
    int result = Calculator.add(3, 4);
    assertThat(result).isEqualTo(7);
}

Official Reference


47. How do you use Hamcrest with JUnit?

Add the Hamcrest dependency in your pom.xml file for Maven projects.

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

Then, you can use Hamcrest matchers in your tests.

Example:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

@Test
public void testAddition() {
    int result = Calculator.add(3, 4);
    assertThat(result, is(equalTo(7)));
}

Official Reference


48. What is the purpose of @Nested in JUnit 5?

@Nested allows you to group and nest tests within a test class.

Example:

public class MyTest {

    @Nested
    class GroupOfTests {

        @Test
        void test1() {
            // Test code
        }

        @Test
        void test2() {
            // Test code
        }
    }
}

Official Reference


49. What is the purpose of @DisplayName in JUnit 5?

@DisplayName is used to provide a custom name for a test or a container.

Example:

@DisplayName("My First Test")
@Test
void myFirstTest() {
    // Test code
}

Official Reference


50. How do you run a single test method in JUnit?

In most IDEs, you can right-click on a test method and select “Run” or “Debug” to run a single test method.

Official Reference


51. What is Parameterized Testing in JUnit?

Parameterized Testing in JUnit allows you to run the same test with different sets of data.

Example:

@RunWith(Parameterized.class)
public class MyParameterizedTest {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
            {1, 1, 2},
            {2, 3, 5},
            {3, 3, 6}
        });
    }

    private int a;
    private int b;
    private int expected;

    public MyParameterizedTest(int a, int b, int expected) {
        this.a = a;
        this.b = b;
        this.expected = expected;
    }

    @Test
    public void testAddition() {
        assertEquals(expected, Calculator.add(a, b));
    }
}

Official Reference


52. What is the purpose of @Before and @After in JUnit?

@Before is used to specify setup code that should run before each test method. @After is used for teardown code after each test method.

Example:

public class MyTest {

    private List<String> list;

    @Before
    public void setUp() {
        list = new ArrayList<>();
    }

    @After
    public void tearDown() {
        list.clear();
    }

    @Test
    public void testListSize() {
        list.add("Item");
        assertEquals(1, list.size());
    }
}

Official Reference

Official Reference


53. What is the purpose of @BeforeClass and @AfterClass in JUnit?

@BeforeClass is used to specify setup code that should run once before all test methods in a class. @AfterClass is used for teardown code after all test methods.

Example:

public class MyTest {

    private static List<String> sharedList;

    @BeforeClass
    public static void setUpClass() {
        sharedList = new ArrayList<>();
    }

    @AfterClass
    public static void tearDownClass() {
        sharedList.clear();
    }

    @Test
    public void testListSize() {
        sharedList.add("Item");
        assertEquals(1, sharedList.size());
    }
}

Official Reference

Official Reference


54. What is the purpose of @Ignore in JUnit?

@Ignore is used to temporarily disable a test.

Example:

public class MyTest {

    @Ignore("This test is currently disabled")
    @Test
    public void testDisabled() {
        // Test code
    }

    @Test
    public void testEnabled() {
        // Test code
    }
}

Official Reference


55. What is the purpose of @Timeout in JUnit?

@Timeout is used to specify a maximum time a test method should take.

Example:

public class MyTest {

    @Test(timeout = 1000)
    public void testTimeout() {
        // Test code
    }
}

Official Reference


56. How do you assert that an exception is thrown in JUnit?

Use @Test with expected attribute or use assertThrows() method from JUnit 4.7 onwards.

Example:

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class MyTest {

    @Test(expected = ArithmeticException.class)
    public void testDivisionByZero() {
        int result = Calculator.divide(10, 0);
    }
}

Official Reference


57. What is the purpose of @RunWith(Parameterized.class)?

@RunWith(Parameterized.class) is used for parameterized tests in JUnit.

Example:

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class MyParameterizedTest {
    // ...
}

Official Reference


58. What is the purpose of @Category in JUnit?

@Category allows you to categorize your tests and run only a specific category of tests.

Example:

import org.junit.Test;
import org.junit.experimental.categories.Category;

public class MyTest {

    @Category(FastTests.class)
    @Test
    public void testFastOperation() {
        // Test code
    }

    @Category(SlowTests.class)
    @Test
    public void testSlowOperation() {
        // Test code
    }
}

Official Reference


59. What is a Test Suite in JUnit?

A Test Suite in JUnit is used to group multiple test cases together.

Example:

@RunWith(Suite.class)
@Suite.SuiteClasses({
   TestClass1.class,
   TestClass2.class
})
public class TestSuite {
    // This class remains empty
}

Official Reference


60. What is the purpose of @RunWith(MockitoJUnitRunner.class)?

@RunWith(MockitoJUnitRunner.class) is used to automatically initialize annotated mocks and spies in JUnit.

Example:

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

    @Mock
    private MyService service;

    @Test
    public void testServiceMethod() {
        when(service.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.getData());
    }
}

Official Reference


61. What is the purpose of @Spy in Mockito?

@Spy is used to create a partial mock of a real object. It allows you to selectively mock some methods.

Example:

public class MyService {

    public int add(int a, int b) {
        return a + b;
    }

    public String getData() {
        return "Real Data";
    }
}

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

    @Spy
    private MyService service;

    @Test
    public void testAddition() {


        int result = service.add(3, 4);
        assertEquals(7, result);
    }

    @Test
    public void testGetData() {
        when(service.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.getData());
    }
}

Official Reference


62. What is the purpose of @Mock in Mockito?

@Mock is used to create a mock of a class or interface.

Example:

@Mock
private MyService service;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

Official Reference


63. What is the purpose of @Captor in Mockito?

@Captor is used to capture arguments passed to a mock object.

Example:

@Captor
private ArgumentCaptor<String> argument;

@Test
public void testAddItem() {
    List<String> mockedList = mock(List.class);
    mockedList.add("Item");

    verify(mockedList).add(argument.capture());

    assertEquals("Item", argument.getValue());
}

Official Reference


64. What is the purpose of @InjectMocks in Mockito?

@InjectMocks is used to inject mocks into the class under test.

Example:

@Mock
private ExternalDependency dependency;

@InjectMocks
private MyService service;

@Test
public void testProcessData() {
    when(dependency.getData()).thenReturn("Mocked Data");
    assertEquals("Mocked Data", service.processData());
}

Official Reference


65. What is the purpose of @RunWith(PowerMockRunner.class)?

@RunWith(PowerMockRunner.class) is used to run tests that mock static methods or suppress constructor execution.

Example:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStaticMethod.class)
public class MyTest {

    @Test
    public void testStaticMethod() {
        PowerMockito.mockStatic(ClassWithStaticMethod.class);
        when(ClassWithStaticMethod.staticMethod()).thenReturn("Mocked Value");

        assertEquals("Mocked Value", ClassWithStaticMethod.staticMethod());
    }
}

Official Reference


66. What is the purpose of @PrepareForTest in PowerMockito?

@PrepareForTest is used to specify which classes should be prepared for mocking static methods or suppressing constructor execution.

Example:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStaticMethod.class)
public class MyTest {
    // ...
}

Official Reference


67. What is the purpose of @SuppressStaticInitializationFor in PowerMockito?

@SuppressStaticInitializationFor is used to suppress the static initialization block of a class.

Example:

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("ClassWithStaticInitializationBlock")
public class MyTest {
    // ...
}

Official Reference


68. What is the purpose of @Rule in JUnit?

@Rule is used to add additional behavior to your tests, such as custom test execution, logging, or timeout.

Example:

@Rule
public Timeout globalTimeout = Timeout.seconds(1);

@Test
public void testTimeSensitiveOperation() {
    // Test code
}

Official Reference


69. What is the purpose of @ClassRule in JUnit?

@ClassRule is used to apply a rule to all the tests in a class.

Example:

@ClassRule
public static ExternalResource resource = new ExternalResource() {
    @Override
    protected void before() throws Throwable {
        // Initialize external resource
    }

    @Override
    protected void after() {
        // Clean up external resource
    }
};

@Test
public void testOperationWithExternalResource() {
    // Test code
}

Official Reference


70. What is the purpose of @RuleChain in JUnit?

@RuleChain allows you to specify the order in which rules are applied.

Example:

@Rule
public RuleChain chain = RuleChain
    .outerRule(new CustomRule1())
    .around(new CustomRule2());

@Test
public void testWithRules() {
    // Test code
}

Official Reference


71. What is the purpose of @TestRule in JUnit?

@TestRule is used to add additional behavior to a test method.

Example:

@Rule
public TestRule customRule = (base, description) -> {
    // Before test logic
    Statement result = base;
    // After test logic
    return result;
};

@Test
public void testWithCustomRule() {
    // Test code
}

Official Reference


72. What is the purpose of @RuleAnnotation in JUnit?

@RuleAnnotation is used to create custom annotations that can be used as rules.

Example:

@Rule
public CustomAnnotationRule customRule = new CustomAnnotationRule();

@Test
@CustomAnnotationRule
public void testWithCustomAnnotationRule() {
    // Test code
}

Official Reference


73. What is the purpose of @Parameterized.Parameters in JUnit?

@Parameterized.Parameters is used to supply a collection of parameters for a parameterized test.

Example:

@Parameterized.Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {
        {1, 1, 2},
        {2, 3, 5},
        {3, 3, 6}
    });
}

Official Reference


74. What is the purpose of @ParametersSuppliedBy in JUnit?

@ParametersSuppliedBy is used to specify a custom supplier for parameters in a parameterized test.

Example:

@ParametersSuppliedBy(MyCustomSupplier.class)
public static Collection<Object[]> data() {
    return null;
}

Official Reference


75. What is the purpose of @UseParametersRunnerFactory in JUnit?

@UseParametersRunnerFactory is used to specify a custom runner factory for parameterized tests.

Example:

@UseParametersRunnerFactory(MyCustomRunnerFactory.class)
public class MyParameterizedTest {
    // ...
}

Official Reference


76. What is the purpose of @UseRunnerDelegate in JUnit?

@UseRunnerDelegate is used to specify a runner delegate for a parameterized test.

Example:

@UseRunnerDelegate(MyRunnerDelegate.class)
public class MyParameterizedTest {
    // ...
}

Official Reference


77. What is the purpose of @Ignore in JUnit?

@Ignore is used to temporarily disable a test.

Example:

@Ignore("This test is currently disabled")
@Test
public void testDisabled() {
    // Test code
}

@Test
public void testEnabled() {
    // Test code
}

Official Reference


78. What is the purpose of @FixMethodOrder in JUnit?

@FixMethodOrder is used to specify the order of execution of test methods.

Example:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyTest {

    @Test
    public void testB() {
        // Test code
    }

    @Test
    public void testA() {
        // Test code
    }
}

Official Reference


79. What is the purpose of @Category in JUnit?

@Category allows you to categorize your tests and run only a specific category of tests.

Example:

@Category(FastTests.class)
@Test
public void testFastOperation() {
    // Test code
}

@Category(SlowTests.class)
@Test
public void testSlowOperation() {
    // Test code
}

Official Reference


80. What is a Test Suite in JUnit?

A Test Suite in JUnit is used to group multiple test cases together.

Example:

@RunWith(Suite.class)
@Suite.SuiteClasses({
   TestClass1.class,
   TestClass2.class
})
public class TestSuite {
    // This class remains empty
}

Official Reference


81. What is the purpose of @RunWith(Parameterized.class)?

@RunWith(Parameterized.class) is used for parameterized tests in JUnit.

Example:

@RunWith(Parameterized.class)
public class MyParameterizedTest {
    // ...
}

Official Reference


82. What is the purpose of @Suite.SuiteClasses in JUnit?

@Suite.SuiteClasses is used to specify which test classes should be included in a test suite.

Example:

@RunWith(Suite.class)
@Suite.SuiteClasses({
   TestClass1.class,
   TestClass2.class
})
public class TestSuite {
    // This class remains empty
}

Official Reference


83. What is the purpose of @RunWith(SpringRunner.class) in Spring Boot?

@RunWith(SpringRunner.class) is used to run Spring tests.

Example:

@RunWith(SpringRunner.class)
public class MySpringTest {
    // ...
}

Official Reference


84. What is the purpose of @SpringBootTest in Spring Boot?

@SpringBootTest is used to load the entire application context for integration testing in Spring Boot.

Example:

@SpringBootTest
public class MyIntegrationTest {
    // ...
}

Official Reference


85. How do you use TestNG with Spring Boot?

You can use the @SpringBootTest annotation from Spring Boot along with TestNG.

Example:

@SpringBootTest
public class MyTestNGIntegrationTest {

    @Autowired
    private MyService service;

    @Test
    public void testServiceMethod() {
        String result = service.getData();
        assertEquals("Expected Result", result);
    }
}

Official Reference


86. How do you use Mockito with Spring Boot?

You can use the @MockBean annotation to mock dependencies in Spring Boot.

Example:

@SpringBootTest
public class MyTest {

    @Autowired
    private MyService service;

    @MockBean
    private ExternalDependency dependency;

    @Test
    public void testServiceMethod() {
        when(dependency.getData()).thenReturn("Mocked Data");
        assertEquals("Mocked Data", service.getData());
    }
}

Official Reference


87. How do you use TestRestTemplate in Spring Boot?

You can use TestRestTemplate to make HTTP requests in integration tests in Spring Boot.

Example:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIntegrationTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @LocalServerPort
    private int port;

    @Test
    public void testRestEndpoint() {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:" + port + "/endpoint", String.class);
        assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
        assertEquals("Expected Response", responseEntity.getBody());
    }
}

Official Reference


88. How do you use JUnit 4 and JUnit 5 in the same project?

You can use both JUnit 4 and JUnit 5 in the same project by including their dependencies and annotations accordingly.

Example:

<!-- JUnit 4 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

<!-- JUnit 5 -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-j

upiter-engine</artifactId>
    <version>5.7.2</version>
    <scope>test</scope>
</dependency>

Official Reference


89. How do you use AssertJ with JUnit?

Add the AssertJ dependency in your pom.xml file for Maven projects.

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.21.0</version>
    <scope>test</scope>
</dependency>

Then, you can use AssertJ assertions in your tests.

Example:

import static org.assertj.core.api.Assertions.assertThat;

@Test
public void testAddition() {
    int result = Calculator.add(3, 4);
    assertThat(result).isEqualTo(7);
}

Official Reference


90. How do you use Hamcrest with JUnit?

Add the Hamcrest dependency in your pom.xml file for Maven projects.

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

Then, you can use Hamcrest matchers in your tests.

Example:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

@Test
public void testAddition() {
    int result = Calculator.add(3, 4);
    assertThat(result, is(equalTo(7)));
}

Official Reference


91. What is the purpose of @Nested in JUnit 5?

@Nested allows you to group and nest tests within a test class.

Example:

public class MyTest {

    @Nested
    class GroupOfTests {

        @Test
        void test1() {
            // Test code
        }

        @Test
        void test2() {
            // Test code
        }
    }
}

Official Reference


92. What is the purpose of @DisplayName in JUnit 5?

@DisplayName is used to provide a custom name for a test or a container.

Example:

@DisplayName("My First Test")
@Test
void myFirstTest() {
    // Test code
}

Official Reference


93. How do you run a single test method in JUnit?

In most IDEs, you can right-click on a test method and select "Run" or "Debug" to run a single test method.

Official Reference


94. What is the purpose of @RepeatedTest in JUnit 5?

@RepeatedTest is used to repeat a test a specified number of times.

Example:

@RepeatedTest(5)
void repeatedTest() {
    // Test code
}

Official Reference


95. What is the purpose of @ParameterizedTest in JUnit 5?

@ParameterizedTest is used for parameterized tests in JUnit 5.

Example:

@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void parameterizedTest(int number) {
    assertTrue(number > 0);
}

Official Reference


96. What is the purpose of @MethodSource in JUnit 5?

@MethodSource is used to specify a method that provides the arguments for a parameterized test.

Example:

@ParameterizedTest
@MethodSource("provideNumbers")
void parameterizedTest(int number) {
    assertTrue(number > 0);
}

private static Stream<Integer> provideNumbers() {
    return Stream.of(1, 2, 3);
}

Official Reference


97. What is the purpose of @CsvSource in JUnit 5?

@CsvSource is used to provide comma-separated values for parameterized tests.

Example:

@ParameterizedTest
@CsvSource({
    "1, true",
    "0, false",
    "-1, false"
})
void parameterizedTest(int input, boolean expected) {
    assertEquals(expected, isPositive(input));
}

private boolean isPositive(int number) {
    return number > 0;
}

Official Reference


98. What is the purpose of @EnumSource in JUnit 5?

@EnumSource is used to provide enum values for parameterized tests.

Example:

enum Day {
    MONDAY, TUESDAY, WEDNESDAY
}

@ParameterizedTest
@EnumSource(Day.class)
void parameterizedTest(Day day) {
    assertNotNull(day);
}

Official Reference


99. What is the purpose of @ValueSource in JUnit 5?

@ValueSource is used to provide a single parameterized value for a test.

Example:

@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void parameterizedTest(int number) {
    assertTrue(number > 0);
}

Official Reference


100. What is the purpose of @CsvFileSource in JUnit 5?

@CsvFileSource is used to provide values from a CSV file for parameterized tests.

Example:

@ParameterizedTest
@CsvFileSource(resources = "/data.csv", numLinesToSkip = 1)
void parameterizedTest(int number, boolean isPositive) {
    assertEquals(isPositive, number > 0);
}

Official Reference