unit test java code example

Example 1: java unit test an api

@Test
public void
  givenUserExists_whenUserInformationIsRetrieved_thenRetrievedResourceIsCorrect()
  throws ClientProtocolException, IOException {
  
    // Given
    HttpUriRequest request = new HttpGet( "https://api.github.com/users/eugenp" );
 
    // When
    HttpResponse response = HttpClientBuilder.create().build().execute( request );
 
    // Then
    GitHubUser resource = RetrieveUtil.retrieveResourceFromResponse(
      response, GitHubUser.class);
    assertThat( "eugenp", Matchers.is( resource.getLogin() ) );
}

Example 2: java junit test

import org.junit.Assert;
import org.junit.Test;

public class Test {

    public static int square(int n) {
        return n * n;
    }

    @Test
    public void squareTest() {
        Assert.assertEquals(25, square(5));
        Assert.assertEquals(16, square(4));
        Assert.assertEquals(9, square(3));
        Assert.assertEquals(4, square(2));
        Assert.assertEquals(1, square(1));
    }
}

Example 3: how to write a junit test case in java

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class MyTests {

    @Test
    public void multiplicationOfZeroIntegersShouldReturnZero() {
        MyClass tester = new MyClass(); // MyClass is tested

        // assert statements
        assertEquals(0, tester.multiply(10, 0), "10 x 0 must be 0");
        assertEquals(0, tester.multiply(0, 10), "0 x 10 must be 0");
        assertEquals(0, tester.multiply(0, 0), "0 x 0 must be 0");
    }
}

Tags:

Java Example