concept unit test in category java

This is an excerpt from Manning's book JUnit in Action.
If you recognize the names Erich Gamma and Kent Beck, that’s for a good reason. Gamma is one of the Gang of Four who gave us the now-classic Design Patterns book.[3] Beck is equally well known for his groundbreaking work in the software discipline known as Extreme Programming (www.extremeprogramming.org).JUnit quickly became the de facto standard framework for developing unit tests in Java. Today, JUnit (https://junit.org) is open source software hosted on GitHub, with an Eclipse Public License. And the underlying testing model, known as xUnit, is on its way to becoming the standard framework for any language. xUnit frameworks are available for ASP, C++, C#, Eiffel, Delphi, Perl, PHP, Python, REBOL, Smalltalk, and Visual Basic—to name just a few.
Why would you need to know all this information? Unit testing is not just something you do without plans and preparations. To become a top-level developer, you need to contrast unit tests with functional and other types of tests. Functional testing simply means that you evaluate the compliance of a system or component with the requirements. When you understand why unit tests are necessary, you need to know how far to take your tests. Testing in and of itself is not the goal.
Listing 11.2 A simple Gradle build.gradle file
plugins { // Apply the java plugin to add support for Java id 'java' // Apply the application plugin to support building a CLI application id 'application' } repositories { // Use jcenter for resolving dependencies. // You can declare any Maven/Ivy/file repository here. jcenter() } dependencies { // Use JUnit Jupiter API for testing. testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' // Use JUnit Jupiter Engine for testing. testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' } application { // Define the main class for the application mainClassName = 'com.manning.junitbook.ch11.App' } test { // Use junit platform for unit tests useJUnitPlatform() }

This is an excerpt from Manning's book Java Testing with Spock.
A common target for unit tests is to handle input data for the system in development. It’s impossible to know all potential uses for your application in advance, let alone the ways people are going to use and misuse your application.
Usually a number of unit tests are dedicated to possible inputs of the system in a gradual way. The test starts with a known set of allowed or disallowed input, and as bugs are encountered, the test is enriched with more cases. Common examples include a test that checks whether a username is valid or which date formats are accepted in a web service.
Let’s say you have a Java class in your application that shuts down a nuclear reactor when radiation levels from a sensor pass a critical threshold. You want to write a unit test for that class. It wouldn’t be realistic to bombard the real sensor with radiation just to see your unit test work. It’s also not realistic to shut down the nuclear reactor whenever the unit test runs.
For a more run-of-the-mill example, assume that your Java class sends a reminder email to a customer whenever an invoice isn’t settled on time. Re-creating a delayed payment in the unit test would be difficult, and sending a real email each time the unit test runs would also be unrealistic.
For cases like this, you need to employ fake collaborators in your unit test. You need to fake the way your class gets the current sensor values as well as the communication with the nuclear reactor, and you also need to fake the delayed payment and the email server. A fake collaborator is a special class that replaces a real class in order to make its behavior deterministic (preprogrammed). No technical limitation ties fake classes to unit tests. But unit tests are much more flexible if they employ the power of fake classes (which is the running theme of this chapter).
If a bug shows up in a real system (or in an integration test), it’s not immediately clear which class or classes are responsible for it. In a unit test that contains only a real class (as in figure 6.1), you can preprogram its collaborators with “correct” and “expected” answers. Thus, it’s easy to focus the unit test on how this single class works and make sure that it contains no bugs (at least on its own).

This is an excerpt from Manning's book Testing Java Microservices: Using Arquillian, Hoverfly, AssertJ, JUnit, Selenium, and Mockito.
As you now know, unit testing is a testing technique where the code of the application under test should be the smallest possible snippet to produce the required behavior. Another main characteristic of unit tests is that they should execute as quickly as possible, so developers get rapid feedback after any addition to or refactoring of the code base.
So far, we’ve written unit tests without having to mock any dependencies. Let’s write a unit test for a repository element. In this case, we’ll use the Games class (code/game/src/main/javahttps://livebook.manning.com/book/games/boundary/Games.java).
Listing 3.5. Games class
@Stateless #1 public class Games { @PersistenceContext #2 EntityManager em; public Long create(final Game request) { final Game game = em.merge(request); #3 return game.getId(); } public Optional<Game> findGameById(final Long gameId) { Optional<Game> g = Optional.ofNullable(em.find(Game.class, gameId)); if (g.isPresent()) { Game game = g.get(); game.getReleaseDates().size(); game.getPublishers().size(); game.getDevelopers().size(); em.detach(game); } return g; } }One of the most important things in unit tests is maintaining a good pace of execution. Because this repository is implemented using JPA, you need to mock this part.
Listing 3.6. Unit test for Games
@RunWith(MockitoJUnitRunner.class) #1 public class GamesTest { private static final long GAME_ID = 123L; @Mock #2 EntityManager entityManager; @Test public void shouldCreateAGame() { final Game game = new Game(); game.setId(GAME_ID); game.setTitle("Zelda"); final Games games = new Games(); when(entityManager.merge(game)).thenReturn(game); #3 games.em = entityManager; #4 games.create(game); #5 verify(entityManager).merge(game); #6 } }This test is slightly different from the previous ones. The first thing to notice is that it uses a custom JUnit runner. This runner is provided by the Mockito framework and is responsible for initializing all fields annotated with @Mock, among other things. You can use Mockito without the JUnit runner by using the Mockito.mock() method, as was shown in the introduction to the Mockito section; but in our opinion, unit tests look clearer when using the runner.
Let’s write a unit test for GamesResource (code/game/src/main/javahttps://livebook.manning.com/book/games/boundary/GamesResource.java). Remember that this class is the definition of REST endpoints related to game operations.

This is an excerpt from Manning's book Portlets in Action.
lib— Contains the JAR files required at build time but that don’t need to be packaged with the generated WAR file, such as JUnit and portlet JAR files. The JUnit JAR file is required to run unit tests at build time, and a portlet JAR file is required for compiling the portlet classes.
Uses the Spring TestContext framework to unit test and integration test controllers

This is an excerpt from Manning's book JUnit in Action, Second Edition.
JUnit quickly became the de facto standard framework for developing unit tests in Java. The underlying testing model, known as xUnit, is on its way to becoming the standard framework for any language. There are xUnit frameworks available for ASP, C++, C#, Eiffel, Delphi, Perl, PHP, Python, REBOL, Smalltalk, and Visual Basic—to name a few!
The JUnit team did not invent software testing or even the unit test. Originally, the term unit test described a test that examined the behavior of a single unit of work.
Over time, usage of the term unit test broadened. For example, IEEE has defined unit testing as “Testing of individual hardware or software units or groups of related units” (emphasis added).[4]
Unit tests must exercise code in isolation; the persistence layer requires interaction with an external entity, the database. Unit tests must be easy to write and run; code that accesses the database can be cumbersome. Unit tests must be fast to run; database access is relatively slow.
It doesn’t matter how much a company, project manager, or technical leader praises unit tests; if they’re not easy to write and run, developers will resist writing them. Moreover, writing code that accesses the database isn’t the sexiest of tasks. One would have to write SQL statements, mix many levels of try-catch-finally code, convert SQL types to and from Java, and so on.