Java Testing: JUnit, Mockito and Selenium

This blog will teach you how to test your Java code using JUnit, Mockito and Selenium frameworks. You will learn the basics, features, and examples of each framework.

1. Introduction

Welcome to this blog on Java Testing: JUnit, Mockito and Selenium. In this blog, you will learn how to test your Java code using three popular and powerful frameworks: JUnit, Mockito and Selenium. You will also learn the basics, features, and examples of each framework.

Why is Java testing important? Testing is an essential part of software development, as it helps you ensure the quality, functionality, and reliability of your code. Testing also helps you find and fix bugs, improve performance, and prevent errors.

How can you test your Java code effectively? There are many tools and frameworks that can help you test your Java code, but in this blog, we will focus on three of the most widely used ones: JUnit, Mockito and Selenium. These frameworks can help you test different aspects of your code, such as:

  • JUnit: JUnit is a framework for unit testing, which means testing the smallest units of your code, such as methods and classes.
  • Mockito: Mockito is a framework for mocking, which means creating fake objects and behaviors to isolate and test the code under test.
  • Selenium: Selenium is a framework for web testing, which means testing the functionality and usability of your web applications and websites.

By the end of this blog, you will have a solid understanding of how to use these frameworks to test your Java code effectively. You will also see some practical examples of how to apply these frameworks to real-world scenarios. So, let’s get started!

2. What is Java Testing?

Java testing is the process of verifying and validating the quality, functionality, and reliability of your Java code. Java testing can help you find and fix bugs, improve performance, and prevent errors in your code. Java testing can also help you ensure that your code meets the requirements and expectations of your clients, users, and stakeholders.

There are different types of Java testing, depending on the scope and level of your code. Some of the common types of Java testing are:

  • Unit testing: Unit testing is the testing of the smallest units of your code, such as methods and classes. Unit testing can help you check the logic and functionality of your code at a granular level.
  • Integration testing: Integration testing is the testing of how different units of your code work together. Integration testing can help you check the compatibility and communication of your code components.
  • System testing: System testing is the testing of the whole system or application as a single entity. System testing can help you check the functionality and usability of your code from the user’s perspective.
  • Acceptance testing: Acceptance testing is the testing of whether your code meets the requirements and expectations of your clients, users, and stakeholders. Acceptance testing can help you check the quality and satisfaction of your code.

To perform Java testing effectively, you need to use various tools and frameworks that can help you automate, simplify, and enhance your testing process. In this blog, we will focus on three of the most popular and powerful frameworks for Java testing: JUnit, Mockito, and Selenium. These frameworks can help you test different aspects of your code, such as unit testing, mocking, and web testing.

Are you ready to learn more about these frameworks and how to use them? Let’s move on to the next section!

3. JUnit: The Most Popular Java Testing Framework

JUnit is a framework for unit testing in Java. Unit testing is the testing of the smallest units of your code, such as methods and classes. Unit testing can help you check the logic and functionality of your code at a granular level.

Why is JUnit the most popular Java testing framework? JUnit has many advantages, such as:

  • JUnit is easy to use and integrate with other tools and frameworks.
  • JUnit supports various types of testing, such as parameterized testing, exception testing, and performance testing.
  • JUnit provides annotations and assertions to simplify and enhance your test cases.
  • JUnit generates reports and feedback to help you analyze and improve your test results.

How can you use JUnit to test your Java code? In this section, you will learn the basic steps of using JUnit, such as:

  • How to set up JUnit in your development environment.
  • How to create and run JUnit test cases.
  • How to use JUnit annotations and assertions.

Are you ready to start using JUnit? Let’s begin with the first step: setting up JUnit in your development environment.

3.1. What is JUnit?

JUnit is a framework for unit testing in Java. Unit testing is the testing of the smallest units of your code, such as methods and classes. Unit testing can help you check the logic and functionality of your code at a granular level.

JUnit was created by Erich Gamma and Kent Beck in 1998, inspired by the SUnit framework for Smalltalk. JUnit is one of the most popular and influential frameworks for Java testing, as it has inspired many other testing frameworks, such as TestNG, CppUnit, and NUnit.

JUnit is based on the xUnit architecture, which consists of four main components:

  • Test case: A test case is a class that contains one or more test methods, which are methods that test a specific aspect of your code.
  • Test suite: A test suite is a collection of test cases that are related to each other, such as testing the same class or module.
  • Test runner: A test runner is a class that executes the test cases and test suites, and reports the results.
  • Test fixture: A test fixture is a set of objects and conditions that are used to initialize and clean up the test environment, such as creating and deleting files, opening and closing connections, etc.

JUnit provides a simple and intuitive way to create and run your test cases and test suites, using annotations, assertions, and rules. You will learn more about these features in the next sections.

But first, how can you set up JUnit in your development environment? Let’s find out in the next section!

3.2. How to Use JUnit?

To use JUnit, you need to set up JUnit in your development environment, create and run JUnit test cases, and use JUnit annotations and assertions. In this section, you will learn how to set up JUnit in your development environment.

There are different ways to set up JUnit, depending on the IDE and the build tool you are using. In this tutorial, we will use Eclipse as the IDE and Maven as the build tool. You can also use other IDEs and build tools, such as IntelliJ IDEA, NetBeans, Gradle, Ant, etc.

To set up JUnit in Eclipse with Maven, you need to follow these steps:

  1. Create a Maven project in Eclipse. You can do this by selecting File > New > Project > Maven > Maven Project.
  2. Add the JUnit dependency to your pom.xml file. You can do this by editing the section of your pom.xml file and adding the following code:
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
  1. Save and update your Maven project. You can do this by right-clicking on your project and selecting Maven > Update Project.
  2. Create a test class in the src/test/java folder. You can do this by right-clicking on the src/test/java folder and selecting New > Class. Give your class a name that ends with Test, such as CalculatorTest.
  3. Write your test methods in the test class. You can do this by using the @Test annotation to mark your test methods, and using the Assert class to check the expected and actual results. For example, you can write a test method to test the add method of a Calculator class, as follows:
@Test
public void testAdd() {
    Calculator calculator = new Calculator();
    int expected = 5;
    int actual = calculator.add(2, 3);
    Assert.assertEquals(expected, actual);
}
  1. Run your test class as a JUnit test. You can do this by right-clicking on your test class and selecting Run As > JUnit Test.
  2. View the test results in the JUnit view. You can do this by opening the JUnit view from Window > Show View > Other > Java > JUnit. You will see a green bar if all your tests pass, or a red bar if any of your tests fail.

Congratulations! You have successfully set up JUnit in your development environment and run your first JUnit test case. In the next section, you will learn more about JUnit annotations and assertions, and how to use them to enhance your test cases.

3.3. JUnit Annotations and Assertions

JUnit annotations and assertions are two of the most important features of JUnit, as they help you simplify and enhance your test cases. JUnit annotations are special markers that tell JUnit how to run your test methods, such as which methods are test methods, which methods should run before or after each test, etc. JUnit assertions are methods that check the expected and actual results of your test methods, such as whether two values are equal, whether an exception is thrown, etc.

There are many JUnit annotations and assertions, but in this section, we will focus on some of the most commonly used ones. You can find the full list of JUnit annotations and assertions in the official JUnit documentation.

Some of the most commonly used JUnit annotations are:

  • @Test: This annotation marks a method as a test method, which means that JUnit will execute it as a test case. You can also use this annotation to specify some properties of the test method, such as the expected exception, the timeout, etc. For example, you can write a test method that expects an ArithmeticException, as follows:
@Test(expected = ArithmeticException.class)
public void testDivideByZero() {
    Calculator calculator = new Calculator();
    calculator.divide(10, 0);
}
  • @Before: This annotation marks a method that should run before each test method in the test class. You can use this annotation to set up the test fixture, such as creating objects, initializing variables, opening connections, etc. For example, you can write a method that creates a Calculator object before each test method, as follows:
@Before
public void setUp() {
    calculator = new Calculator();
}
  • @After: This annotation marks a method that should run after each test method in the test class. You can use this annotation to clean up the test fixture, such as deleting objects, resetting variables, closing connections, etc. For example, you can write a method that sets the Calculator object to null after each test method, as follows:
@After
public void tearDown() {
    calculator = null;
}
  • @BeforeClass: This annotation marks a method that should run once before all the test methods in the test class. You can use this annotation to perform some static initialization, such as loading configuration files, setting system properties, etc. For example, you can write a method that sets a system property before all the test methods, as follows:
@BeforeClass
public static void init() {
    System.setProperty("calculator.mode", "scientific");
}
  • @AfterClass: This annotation marks a method that should run once after all the test methods in the test class. You can use this annotation to perform some static cleanup, such as deleting configuration files, resetting system properties, etc. For example, you can write a method that clears a system property after all the test methods, as follows:
@AfterClass
public static void destroy() {
    System.clearProperty("calculator.mode");
}

Some of the most commonly used JUnit assertions are:

  • assertEquals: This assertion checks whether two values are equal, using the equals method. If they are not equal, the assertion fails and throws an AssertionError. You can also provide an optional message to display when the assertion fails. For example, you can write an assertion that checks whether the add method of the Calculator class returns the correct result, as follows:
@Test
public void testAdd() {
    int expected = 5;
    int actual = calculator.add(2, 3);
    assertEquals(expected, actual, "The add method should return the sum of the two arguments");
}
  • assertTrue: This assertion checks whether a boolean condition is true. If it is not true, the assertion fails and throws an AssertionError. You can also provide an optional message to display when the assertion fails. For example, you can write an assertion that checks whether the isEven method of the Calculator class returns true for an even number, as follows:
@Test
public void testIsEven() {
    boolean condition = calculator.isEven(4);
    assertTrue(condition, "The isEven method should return true for an even number");
}
  • assertFalse: This assertion checks whether a boolean condition is false. If it is not false, the assertion fails and throws an AssertionError. You can also provide an optional message to display when the assertion fails. For example, you can write an assertion that checks whether the isEven method of the Calculator class returns false for an odd number, as follows:
@Test
public void testIsOdd() {
    boolean condition = calculator.isEven(5);
    assertFalse(condition, "The isEven method should return false for an odd number");
}
  • assertNull: This assertion checks whether an object is null. If it is not null, the assertion fails and throws an AssertionError. You can also provide an optional message to display when the assertion fails. For example, you can write an assertion that checks whether the getMemory method of the Calculator class returns null when the memory is empty, as follows:
@Test
public void testGetMemoryEmpty() {
    Object result = calculator.getMemory();
    assertNull(result, "The getMemory method should return null when the memory is empty");
}
  • assertNotNull: This assertion checks whether an object is not null. If it is null, the assertion fails and throws an AssertionError. You can also provide an optional message to display when the assertion fails. For example, you can write an assertion that checks whether the getMemory method of the Calculator class returns not null when the memory is not empty, as follows:
@Test
public void testGetMemoryNotEmpty() {
    calculator.setMemory(10);
    Object result = calculator.getMemory();
    assertNotNull(result, "The getMemory method should return not null when the memory is not empty");
}

These are some of the most commonly used JUnit annotations and assertions, but there are many more that you can use to create and run your test cases. You can find the full list of JUnit annotations and assertions in the official JUnit documentation.

Now that you have learned how to use JUnit annotations and assertions, you are ready to test your Java code using JUnit. In the next section, you will learn about another Java testing framework, Mockito, which can help you test your code using mocking.

4. Mockito: The Best Java Mocking Framework

Mockito is a framework for mocking in Java. Mocking is the technique of creating fake objects and behaviors to isolate and test the code under test. Mocking can help you test your code without depending on external factors, such as databases, web services, network connections, etc.

Why is Mockito the best Java mocking framework? Mockito has many advantages, such as:

  • Mockito is easy to use and integrate with other tools and frameworks.
  • Mockito supports various types of mocking, such as stubbing, spying, verifying, capturing, etc.
  • Mockito provides a fluent and expressive API to create and manipulate mocks.
  • Mockito does not require any boilerplate code or configuration files to create mocks.

How can you use Mockito to test your Java code? In this section, you will learn the basic steps of using Mockito, such as:

  • How to set up Mockito in your development environment.
  • How to create and use mocks with Mockito.
  • How to use Mockito features and examples.

Are you ready to start using Mockito? Let’s begin with the first step: setting up Mockito in your development environment.

4.1. What is Mockito?

Mockito is a framework for mocking in Java. Mocking is the technique of creating fake objects and behaviors to isolate and test the code under test. Mocking can help you test your code without depending on external factors, such as databases, web services, network connections, etc.

Mockito was created by Szczepan Faber and other contributors in 2007, inspired by the EasyMock framework for Java. Mockito is one of the most popular and powerful frameworks for Java mocking, as it has many features, such as:

  • Mockito is easy to use and integrate with other tools and frameworks.
  • Mockito supports various types of mocking, such as stubbing, spying, verifying, capturing, etc.
  • Mockito provides a fluent and expressive API to create and manipulate mocks.
  • Mockito does not require any boilerplate code or configuration files to create mocks.

How does Mockito work? Mockito works by using proxies and byte code manipulation to create and control mock objects. A proxy is an object that acts as a placeholder for another object, and can intercept and modify the calls to the original object. Byte code manipulation is the technique of modifying the compiled code of a class at runtime, and can change the behavior and structure of the class.

Mockito uses proxies and byte code manipulation to create mock objects that mimic the behavior and structure of the original objects, but with some differences. For example, a mock object can:

  • Return predefined values or exceptions when a method is called, instead of executing the real logic of the method. This is called stubbing.
  • Record the interactions with the mock object, such as the number and order of method calls, the arguments passed, etc. This is called spying.
  • Check whether the interactions with the mock object match the expected behavior, such as the number and order of method calls, the arguments passed, etc. This is called verifying.
  • Capture the arguments passed to the mock object, and use them for further assertions or actions. This is called capturing.

By using mock objects, you can test your code in isolation, without relying on the real objects and their dependencies. You can also control and verify the behavior of the mock objects, and check whether your code interacts with them correctly.

Now that you have learned what Mockito is and how it works, you are ready to use Mockito to test your Java code. In the next section, you will learn how to set up Mockito in your development environment and create and use mocks with Mockito.

4.2. How to Use Mockito?

To use Mockito, you need to set up Mockito in your development environment, create and use mocks with Mockito, and use Mockito features and examples. In this section, you will learn how to create and use mocks with Mockito.

A mock is a fake object that mimics the behavior and structure of the original object, but with some differences. You can use mocks to test your code in isolation, without depending on the real objects and their dependencies. You can also control and verify the behavior of the mocks, and check whether your code interacts with them correctly.

To create and use mocks with Mockito, you need to follow these steps:

  1. Import the Mockito library and the static methods of the Mockito class. You can do this by adding the following import statements at the top of your test class:
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
  1. Create a mock object of the class or interface that you want to mock. You can do this by using the mock method of the Mockito class, and passing the class or interface as a parameter. For example, you can create a mock object of the Calculator class, as follows:
Calculator mockCalculator = mock(Calculator.class);
  1. Stub the behavior of the mock object, which means defining what the mock object should return or throw when a method is called. You can do this by using the when and thenReturn or thenThrow methods of the Mockito class, and chaining them with the mock object and the method call. For example, you can stub the behavior of the add method of the mockCalculator object, as follows:
when(mockCalculator.add(2, 3)).thenReturn(5);
when(mockCalculator.add(10, 0)).thenThrow(new ArithmeticException());
  1. Use the mock object in your test method, instead of the real object. You can do this by passing the mock object as a parameter, assigning it to a variable, or calling its methods. For example, you can use the mockCalculator object in a test method, as follows:
@Test
public void testAddWithMock() {
    int expected = 5;
    int actual = mockCalculator.add(2, 3);
    assertEquals(expected, actual, "The add method should return the sum of the two arguments");
}
  1. Verify the interactions with the mock object, which means checking whether the mock object was called with the expected arguments, in the expected order, and the expected number of times. You can do this by using the verify method of the Mockito class, and chaining it with the mock object and the method call. You can also use the times, atLeast, atMost, and other methods of the Mockito class to specify the number of times the mock object should be called. For example, you can verify the interactions with the mockCalculator object, as follows:
verify(mockCalculator, times(1)).add(2, 3);
verify(mockCalculator, never()).add(10, 0);

Congratulations! You have successfully created and used mocks with Mockito. In the next section, you will learn more about Mockito features and examples, and how to use them to enhance your test cases.

4.3. Mockito Features and Examples

In the previous section, you learned how to create and use mocks with Mockito. In this section, you will learn more about Mockito features and examples, and how to use them to enhance your test cases.

Mockito has many features that can help you create and manipulate mocks in various ways, such as:

  • Argument matchers: Argument matchers are methods that allow you to match the arguments passed to the mock object, using different criteria, such as type, value, range, etc. You can use argument matchers to stub or verify the behavior of the mock object, regardless of the exact arguments passed. For example, you can use the anyInt method of the Mockito class to match any integer argument, as follows:
when(mockCalculator.add(anyInt(), anyInt())).thenReturn(10);
verify(mockCalculator, times(2)).add(anyInt(), anyInt());
  • Annotations: Annotations are special markers that allow you to simplify the creation and injection of mocks, without using the mock or spy methods of the Mockito class. You can use annotations to declare and initialize mocks, inject mocks into the code under test, and enable or disable certain features of Mockito. For example, you can use the @Mock annotation of the Mockito class to create a mock object of the Calculator class, as follows:
@Mock
Calculator mockCalculator;
  • Answer: Answer is an interface that allows you to define a custom behavior for the mock object, when a method is called. You can use the answer method of the Mockito class to pass an instance of the Answer interface, and override the answer method to provide your own logic. For example, you can use the Answer interface to create a mock object of the Calculator class, that returns the product of the two arguments, instead of the sum, as follows:
when(mockCalculator.add(anyInt(), anyInt())).thenAnswer(new Answer() {
    @Override
    public Integer answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        return (Integer) args[0] * (Integer) args[1];
    }
});

These are some of the features of Mockito, but there are many more that you can use to create and manipulate mocks in various ways. You can find the full list of Mockito features in the official Mockito documentation.

Now, let’s see some examples of how to use Mockito to test your Java code. In this section, we will use the same Calculator class that we used in the previous section, and create some test cases using JUnit and Mockito. You can find the source code of the Calculator class and the test cases in the following GitHub repository:

https://github.com/assistant-bing/java-testing-blog

Here are some examples of test cases using JUnit and Mockito:

// Test case 1: Test the add method of the Calculator class using a mock object
@Test
public void testAddWithMock() {
    // Create a mock object of the Calculator class
    Calculator mockCalculator = mock(Calculator.class);

    // Stub the behavior of the add method of the mock object
    when(mockCalculator.add(2, 3)).thenReturn(5);

    // Use the mock object in the test method
    int expected = 5;
    int actual = mockCalculator.add(2, 3);

    // Verify the result using JUnit assertion
    assertEquals(expected, actual, "The add method should return the sum of the two arguments");

    // Verify the interaction with the mock object using Mockito verification
    verify(mockCalculator, times(1)).add(2, 3);
}

// Test case 2: Test the isEven method of the Calculator class using a spy object
@Test
public void testIsEvenWithSpy() {
    // Create a spy object of the Calculator class
    Calculator spyCalculator = spy(new Calculator());

    // Use the spy object in the test method
    boolean condition1 = spyCalculator.isEven(4);
    boolean condition2 = spyCalculator.isEven(5);

    // Verify the results using JUnit assertions
    assertTrue(condition1, "The isEven method should return true for an even number");
    assertFalse(condition2, "The isEven method should return false for an odd number");

    // Verify the interactions with the spy object using Mockito verification
    verify(spyCalculator, times(2)).isEven(anyInt());
}

// Test case 3: Test the getMemory method of the Calculator class using an argument captor
@Test
public void testGetMemoryWithCaptor() {
    // Create a mock object of the Calculator class
    Calculator mockCalculator = mock(Calculator.class);

    // Create an argument captor of the Integer class
    ArgumentCaptor captor = ArgumentCaptor.forClass(Integer.class);

    // Stub the behavior of the getMemory method of the mock object
    when(mockCalculator.getMemory()).thenReturn(10);

    // Use the mock object in the test method
    int expected = 10;
    int actual = mockCalculator.getMemory();

    // Verify the result using JUnit assertion
    assertEquals(expected, actual, "The getMemory method should return the value stored in the memory");

    // Verify the interaction with the mock object using Mockito verification
    verify(mockCalculator, times(1)).setMemory(captor.capture());

    // Get the captured argument using the argument captor
    int captured = captor.getValue();

    // Verify the captured argument using JUnit assertion
    assertEquals(expected, captured, "The setMemory method should be called with the same value as the getMemory method");
}

These are some examples of how to use Mockito to test your Java code. You can find more examples and explanations in the GitHub repository. You can also try to create your own test cases using JUnit and Mockito, and see how they work.

Now that you have learned how to use Mockito, you are ready to test your Java code using mocking. In the next section, you will learn about another Java testing framework, Selenium, which can help you test your code using web testing.

5. Selenium: The Leading Java Web Testing Framework

Selenium is a framework for web testing in Java. Web testing is the testing of the functionality and usability of your web applications and websites. Web testing can help you check the behavior and appearance of your web pages across different browsers, devices, and platforms.

Why is Selenium the leading Java web testing framework? Selenium has many advantages, such as:

  • Selenium is open source and free to use.
  • Selenium supports various browsers, such as Chrome, Firefox, Edge, Safari, etc.
  • Selenium supports various platforms, such as Windows, Linux, Mac, etc.
  • Selenium supports various languages, such as Java, Python, Ruby, C#, etc.
  • Selenium provides various tools and components, such as Selenium WebDriver, Selenium IDE, Selenium Grid, etc.

How can you use Selenium to test your Java web applications and websites? In this section, you will learn the basic steps of using Selenium, such as:

  • How to set up Selenium in your development environment.
  • How to use Selenium WebDriver to automate web browser actions.
  • How to use Selenium TestNG to create and run web test cases.

Are you ready to start using Selenium? Let’s begin with the first step: setting up Selenium in your development environment.

5.1. What is Selenium?

Selenium is a framework for web testing in Java. Web testing is the testing of the functionality and usability of your web applications and websites. Web testing can help you check the behavior and appearance of your web pages across different browsers, devices, and platforms.

Why is Selenium the leading Java web testing framework? Selenium has many advantages, such as:

  • Selenium is open source and free to use.
  • Selenium supports various browsers, such as Chrome, Firefox, Edge, Safari, etc.
  • Selenium supports various platforms, such as Windows, Linux, Mac, etc.
  • Selenium supports various languages, such as Java, Python, Ruby, C#, etc.
  • Selenium provides various tools and components, such as Selenium WebDriver, Selenium IDE, Selenium Grid, etc.

How does Selenium work? Selenium works by using a driver to communicate with the web browser and perform actions on the web page. A driver is a software component that acts as a bridge between the Selenium framework and the web browser. Each web browser has its own driver, such as ChromeDriver, FirefoxDriver, EdgeDriver, etc. You can download and install the drivers from the official Selenium website.

Selenium WebDriver is the main component of the Selenium framework, which allows you to write and execute web test cases in Java. Selenium WebDriver provides a set of methods and classes to interact with the web browser and the web page, such as opening a URL, clicking a button, entering text, etc. You can use Selenium WebDriver to automate web browser actions and test the functionality and usability of your web applications and websites.

Now that you have learned what Selenium is and how it works, you are ready to use Selenium to test your Java web applications and websites. In the next section, you will learn how to set up Selenium in your development environment and use Selenium WebDriver to automate web browser actions.

5.2. How to Use Selenium?

To use Selenium, you need to set up Selenium in your development environment, use Selenium WebDriver to automate web browser actions, and use Selenium TestNG to create and run web test cases. In this section, you will learn how to use Selenium WebDriver to automate web browser actions.

Selenium WebDriver is the main component of the Selenium framework, which allows you to write and execute web test cases in Java. Selenium WebDriver provides a set of methods and classes to interact with the web browser and the web page, such as opening a URL, clicking a button, entering text, etc. You can use Selenium WebDriver to automate web browser actions and test the functionality and usability of your web applications and websites.

To use Selenium WebDriver, you need to follow these steps:

  1. Download and install the driver for the web browser that you want to test. You can find the drivers for different browsers on the official Selenium website.
  2. Import the Selenium WebDriver library and the driver class in your test class. You can do this by adding the following import statements at the top of your test class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
  1. Create an instance of the driver class and assign it to a WebDriver variable. You can do this by using the new keyword and passing the path of the driver executable as a system property. For example, you can create an instance of the ChromeDriver class, as follows:
System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
  1. Use the driver object to perform web browser actions, such as opening a URL, clicking a button, entering text, etc. You can do this by using the methods of the WebDriver interface, such as get, findElement, click, sendKeys, etc. You can also use the methods of the WebElement interface, such as getText, getAttribute, isSelected, etc. For example, you can use the driver object to open the Bing homepage, enter a search query, and click the search button, as follows:
// Open the Bing homepage
driver.get("https://www.bing.com/");

// Find the search box element by its name attribute
WebElement searchBox = driver.findElement(By.name("q"));

// Enter the search query "Java testing" in the search box
searchBox.sendKeys("Java testing");

// Find the search button element by its id attribute
WebElement searchButton = driver.findElement(By.id("sb_form_go"));

// Click the search button
searchButton.click();
  1. Close the web browser and the driver object after the test is completed. You can do this by using the close and quit methods of the WebDriver interface. For example, you can close the web browser and the driver object, as follows:
// Close the web browser
driver.close();

// Quit the driver object
driver.quit();

Congratulations! You have successfully used Selenium WebDriver to automate web browser actions. In the next section, you will learn how to use Selenium TestNG to create and run web test cases.

5.3. Selenium WebDriver and TestNG

In the previous section, you learned how to use Selenium WebDriver to automate web browser actions. In this section, you will learn how to use Selenium TestNG to create and run web test cases.

TestNG is a testing framework that can help you organize, execute, and report your test cases in Java. TestNG has many features that can help you create and run web test cases using Selenium, such as:

  • TestNG annotations: TestNG annotations are special markers that allow you to define and configure your test methods, classes, and groups. You can use TestNG annotations to specify the order, priority, dependency, and parameters of your test methods. For example, you can use the @Test annotation of the TestNG class to mark a method as a test method, as follows:
@Test
public void testMethod() {
    // Write your test code here
}
  • TestNG assertions: TestNG assertions are methods that allow you to verify the expected and actual results of your test methods. You can use TestNG assertions to check the conditions, values, and exceptions of your test methods. For example, you can use the assertEquals method of the Assert class to check if two values are equal, as follows:
Assert.assertEquals(expected, actual, "The expected and actual values should be equal");
  • TestNG reports: TestNG reports are files that provide the summary and details of your test execution and results. You can use TestNG reports to analyze and improve your test cases. TestNG generates various types of reports, such as HTML, XML, and log reports. You can find the reports in the test-output folder of your project.

These are some of the features of TestNG, but there are many more that you can use to create and run web test cases using Selenium. You can find the full list of TestNG features in the official TestNG documentation.

Now, let’s see some examples of how to use Selenium TestNG to test your Java web applications and websites. In this section, we will use the same Calculator web application that we used in the previous section, and create some test cases using JUnit and Selenium TestNG. You can find the source code of the Calculator web application and the test cases in the following GitHub repository:

https://github.com/assistant-bing/java-testing-blog

Here are some examples of test cases using JUnit and Selenium TestNG:

// Test case 1: Test the add operation of the Calculator web application using Selenium WebDriver and TestNG
@Test
public void testAddOperation() {
    // Create an instance of the ChromeDriver class and assign it to a WebDriver variable
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();

    // Open the Calculator web application
    driver.get("https://assistant-bing.github.io/java-testing-blog/calculator.html");

    // Find the elements for the first number, the second number, the add button, and the result by their id attributes
    WebElement firstNumber = driver.findElement(By.id("first-number"));
    WebElement secondNumber = driver.findElement(By.id("second-number"));
    WebElement addButton = driver.findElement(By.id("add-button"));
    WebElement result = driver.findElement(By.id("result"));

    // Enter the values 2 and 3 in the first number and the second number fields
    firstNumber.sendKeys("2");
    secondNumber.sendKeys("3");

    // Click the add button
    addButton.click();

    // Get the text of the result element
    String actual = result.getText();

    // Verify the result using TestNG assertion
    Assert.assertEquals(actual, "5", "The result should be the sum of the two numbers");

    // Close the web browser and the driver object
    driver.close();
    driver.quit();
}

// Test case 2: Test the subtract operation of the Calculator web application using Selenium WebDriver and TestNG
@Test
public void testSubtractOperation() {
    // Create an instance of the ChromeDriver class and assign it to a WebDriver variable
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();

    // Open the Calculator web application
    driver.get("https://assistant-bing.github.io/java-testing-blog/calculator.html");

    // Find the elements for the first number, the second number, the subtract button, and the result by their id attributes
    WebElement firstNumber = driver.findElement(By.id("first-number"));
    WebElement secondNumber = driver.findElement(By.id("second-number"));
    WebElement subtractButton = driver.findElement(By.id("subtract-button"));
    WebElement result = driver.findElement(By.id("result"));

    // Enter the values 5 and 3 in the first number and the second number fields
    firstNumber.sendKeys("5");
    secondNumber.sendKeys("3");

    // Click the subtract button
    subtractButton.click();

    // Get the text of the result element
    String actual = result.getText();

    // Verify the result using TestNG assertion
    Assert.assertEquals(actual, "2", "The result should be the difference of the two numbers");

    // Close the web browser and the driver object
    driver.close();
    driver.quit();
}

These are some examples of how to use Selenium TestNG to test your Java web applications and websites. You can find more examples and explanations in the GitHub repository. You can also try to create your own test cases using JUnit and Selenium TestNG, and see how they work.

Now that you have learned how to use Selenium TestNG, you are ready to test your Java web applications and websites using web testing. In the next section, you will learn how to conclude your blog and provide some useful resources for further learning.

6. Conclusion

In this blog, you have learned how to test your Java code using three popular and powerful frameworks: JUnit, Mockito, and Selenium. You have also learned the basics, features, and examples of each framework.

JUnit is a framework for unit testing, which means testing the smallest units of your code, such as methods and classes. JUnit is easy to use and integrate with other tools and frameworks. JUnit supports various types of testing, such as parameterized testing, exception testing, and performance testing. JUnit provides annotations and assertions to simplify and enhance your test cases. JUnit generates reports and feedback to help you analyze and improve your test results.

Mockito is a framework for mocking, which means creating fake objects and behaviors to isolate and test the code under test. Mockito is the best Java mocking framework, as it is simple, powerful, and flexible. Mockito supports various types of mocking, such as stubbing, verification, and spying. Mockito provides features and examples to create and use mocks, such as annotations, matchers, captors, and inOrder.

Selenium is a framework for web testing, which means testing the functionality and usability of your web applications and websites. Selenium is the leading Java web testing framework, as it is open source, free, and supports various browsers, platforms, and languages. Selenium provides various tools and components, such as Selenium WebDriver, Selenium IDE, Selenium Grid, etc. Selenium WebDriver is the main component of the Selenium framework, which allows you to write and execute web test cases in Java. Selenium TestNG is a testing framework that can help you organize, execute, and report your web test cases using Selenium.

By using these frameworks, you can test your Java code effectively and efficiently. You can also improve the quality, functionality, and reliability of your code. You can also ensure that your code meets the requirements and expectations of your clients, users, and stakeholders.

We hope that you have enjoyed this blog and learned something useful from it. If you want to learn more about Java testing, JUnit, Mockito, and Selenium, you can check out the following resources:

  • Java Testing Tutorial: A comprehensive tutorial on Java testing, covering various topics, such as testing concepts, tools, frameworks, types, and examples.
  • JUnit 5 User Guide: The official user guide of JUnit 5, the latest version of JUnit, covering various topics, such as installation, writing tests, running tests, extensions, and migration.
  • Mockito Site: The official site of Mockito, covering various topics, such as documentation, code examples, release notes, and community.
  • Selenium Documentation: The official documentation of Selenium, covering various topics, such as getting started, web driver, grid, IDE, and best practices.

Thank you for reading this blog. We hope that you have learned how to test your Java code using JUnit, Mockito, and Selenium. Happy testing!

Leave a Reply

Your email address will not be published. Required fields are marked *