Acharya | MASTERING UNIT TESTING USING MOCKITO AND JUNIT | E-Book | www.sack.de
E-Book

E-Book, Englisch, 314 Seiten

Acharya MASTERING UNIT TESTING USING MOCKITO AND JUNIT

An advanced guide to mastering unit testing using Mockito and JUnit
1. Auflage 2025
ISBN: 978-1-78398-251-6
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)

An advanced guide to mastering unit testing using Mockito and JUnit

E-Book, Englisch, 314 Seiten

ISBN: 978-1-78398-251-6
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)



A practical and easy-to-follow, yet comprehensive, guide to learning advanced JUnit testing. Each topic is explained and placed in context, and for the more inquisitive, there are more details of the concepts used. This book is for you if you are a developer with some experience in Java application development as well as a basic knowledge of JUnit testing. But for those whose skill set is void of any prior experience with JUnit testing, the book also covers basic fundamentals to get you acquainted with the concepts before putting them into practise.

Acharya MASTERING UNIT TESTING USING MOCKITO AND JUNIT jetzt bestellen!

Autoren/Hrsg.


Weitere Infos & Material


Working with JUnit 4


JUnit is a unit testing framework for Java. It allows developers to unit test the code elegantly. Apparently, TestNG is cleaner than JUnit, but JUnit is far more popular than TestNG. JUnit has a better mocking framework support such as Mockito, which offers a custom JUnit 4 runner.

The latest version of JUnit (4.11) can be downloaded from https://github.com/junit-team/junit/wiki/Download-and-Install.

JUnit 4 is an annotation-based, flexible framework. Its predecessor has many downsides. The following are the advantages of JUnit 4 over its predecessor:

  • Instead of inheriting from , any class can be a test class
  • The and methods are replaced by the and annotations
  • Any public method annotated as can be a test method

In this chapter, we will use Eclipse to execute the JUnit tests; in the following chapters, we will be using Ant, Maven, and Gradle to execute tools. Eclipse is an integrated development environment, and can be used to develop applications in Java. It can be downloaded from http://www.eclipse.org/downloads/. As of today, the latest IDE version is KEPLER (4.3).

Note


Since 2006, Eclipse releases a project annually. It started with the name Callisto (starts with a C). Lexicographically, Eclipse project names go like C, E, G, H, I, J, K, and L.

In 2014, they will release the Luna (which starts with L) version. Between 2006 and now, they released Europa (E), Ganymede (G), Galileo (G), Helios (H), Indigo (I), Juno (J), and Kepler (K).

In the following section, we will set up Eclipse and execute our first JUnit test.

Setting up Eclipse


You can skip this section if you know how to install Eclipse and add JUnit JAR to the project. The following are the steps to set up Eclipse:

  1. Visit http://www.eclipse.org/downloads/. From the dropdown, select the operating system—Windows, Mac, or Linux—and then click on the hardware architecture hyperlink, that is, 32 Bit or 64 Bit, and download the binary, as shown in the following screenshot:
  2. Extract the binary and launch Eclipse, for example, click on in Windows to launch Eclipse.
  3. Create a new workspace (for example, in Windows, enter or in Linux or Mac enter ; Eclipse will create the directories). Once the workspace is open, press + or navigate to File | New; it will open a wizard. Select Java Project and click on Next. Enter as the project name and click on Finish. This will create a Java project named .
  4. Download the and packages from https://github.com/junit-team/junit/wiki/Download-and-Install and copy the jars to the project folder.
  5. You can add the JAR to the project in two ways; either right-click on both JAR, select Build Path, and then click on Add to build path. Or, right-click on the project and select the Properties menu item. Click on Java build path on the left-hand side and open the Libraries tab. Then, click on the Add JARs... button, and it will open a pop-up window. Expand the JUnitTests project from the pop up, select the two JAR ( and ), and add them to Libraries. We are now ready with the Eclipse setup.

Running the first unit test


JUnit 4 is an annotation-based framework. It doesn't force you to extend the class. Any Java class can act as a test. In this section, we will uncover the JUnit 4 annotations, assertions, and exceptions.

We will examine the annotations before writing our first test.

Exploring annotations


The annotation represents a test. Any method can be annotated with the annotation with to make it a test method. There's no need to start the method name with test.

We need data to verify a piece of code. For example, if a method takes a list of students and sorts them based on the marks obtained, then we have to build a list of students to test the method. This is called data setup. To perform the data setup, JUnit 3 defines a method in the class. A test class can override the method. The method signature is as follows:

protected void setUp() throws Exception

JUnit 4 provides a annotation. If we annotate any method of any name with , then that method gets executed before every test execution.

Similarly, any method annotated with gets executed after each test method execution. JUnit 3 has a method for this purpose.

JUnit 4 provides two more annotations: and . They are executed only once per test class. The and annotations can be used with any public static void methods. The annotation is executed before the first test and the annotation is executed after the last test. The following example explains the annotation usage and the execution sequence of the annotated methods.

Let's write our first test by performing the following steps:

  1. We will create a test class under a test source package. Create a Source folder named and create a Java class under package .

    It is a good practice to create test classes with a suffix. So, a class will have a test class. Some code coverage tools ignore tests if they don't end with a suffix.

  2. Add the following code to the class:
    import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class SanityTest { @BeforeClass public static void beforeClass() { System.out.println("***Before Class is invoked"); } @Before public void before() { System.out.println("____________________"); System.out.println("\t Before is invoked"); } @After public void after() { System.out.println("\t After is invoked"); System.out.println("================="); } @Test public void someTest() { System.out.println("\t\t someTest is invoked"); } @Test public void someTest2() { System.out.println("\t\t someTest2 is invoked"); } @AfterClass public static void afterClass() { System.out.println("***After Class is invoked"); } }

    Tip


    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    In the preceding class, we created six methods. Two test methods are annotated with . Note that two methods ( and ) are and the other four are nonstatic. A static method annotated with is invoked only once, that is, before the test class is instantiated, and is invoked after the class is done with all the execution.

  3. Run the test. Press + + and or navigate to Run | Run As | JUnit Test. You will see the following console () output:

    Check whether the and methods are...


Acharya Sujoy :

Sujoy Acharya works as a Principal Engineer with Cerner. While growing up, he pursued his interests in the fields of computer science and engineering. His hobbies are watching movies and sitcoms, playing outdoor sports, and reading books. Sujoy likes to research upcoming technologies. His major contributions are in the fields of TDD, building scalable applications, cloud services, and the Spring Framework. He has authored four books for Packt, namely, Test-Driven Development with Mockito, Mastering Unit Testing using Mockito and JUnit, Mockito Essentials, and Mockito for Spring.



Ihre Fragen, Wünsche oder Anmerkungen
Vorname*
Nachname*
Ihre E-Mail-Adresse*
Kundennr.
Ihre Nachricht*
Lediglich mit * gekennzeichnete Felder sind Pflichtfelder.
Wenn Sie die im Kontaktformular eingegebenen Daten durch Klick auf den nachfolgenden Button übersenden, erklären Sie sich damit einverstanden, dass wir Ihr Angaben für die Beantwortung Ihrer Anfrage verwenden. Selbstverständlich werden Ihre Daten vertraulich behandelt und nicht an Dritte weitergegeben. Sie können der Verwendung Ihrer Daten jederzeit widersprechen. Das Datenhandling bei Sack Fachmedien erklären wir Ihnen in unserer Datenschutzerklärung.