• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Testing | JUnit: Unit tests examples
  1. The POM file (pom.xml)
  2. Mockito: some assertions examples
  3. TemporaryFolder: saving/reading data to/from files, copying files
  4. WireMock: testing an HttpGet request

  1. The POM file (pom.xml)
    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>mtitek.junit.samples</groupId>
        <artifactId>mtitek-junit-samples</artifactId>
        <packaging>jar</packaging>
        <version>1.0.0-SNAPSHOT</version>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    
            <maven.compiler.source>19</maven.compiler.source> <!-- maven-compiler-plugin property -->
            <maven.compiler.target>19</maven.compiler.target> <!-- maven-compiler-plugin property -->
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
                <version>5.0.0</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>com.github.tomakehurst</groupId>
                <artifactId>wiremock</artifactId>
                <version>2.27.2</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.4.16</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.14</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.11.0</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.10.1</version>
                </plugin>
            </plugins>
        </build>
    </project>
  2. Mockito: some assertions examples
    src/main/java/mtitek/junit/samples/MyAbc.java:
    package mtitek.junit.samples;
    
    public class MyAbc {
        public Integer offset = 1;
    
        public Integer add(final Integer v1, final Integer v2) {
            return v1 + v2;
        }
    
        public Integer div(final Integer v1, final Integer v2) {
            return v1 / v2;
        }
    
        public void initOffset(final Integer v1) {
            this.offset = v1;
        }
    }
    src/test/java/mtitek/junit/samples/MockitoTest.java:
    package mtitek.junit.samples;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.mockito.ArgumentMatchers;
    import org.mockito.Mockito;
    
    public class MockitoTest {
        @Test
        public void testMockito() {
            final MyAbc myAbc = Mockito.mock(MyAbc.class);
    
            // when
            Mockito.when(myAbc.add(ArgumentMatchers.anyInt(), ArgumentMatchers.any(Integer.class))).thenReturn(1);
            Assert.assertEquals(myAbc.add(1, 2), Integer.valueOf(1));
    
            // verify
            Mockito.verify(myAbc, Mockito.times(1)).add(1, 2);
            Mockito.verify(myAbc, Mockito.never()).add(1, 3);
    
            // thenAnswer
            Mockito.when(myAbc.div(ArgumentMatchers.eq(8), ArgumentMatchers.eq(4)))
                    .thenAnswer(invocationOnMock -> invocationOnMock.getArgument(0, Integer.class)
                            / invocationOnMock.getArgument(1, Integer.class));
            Assert.assertEquals(myAbc.div(8, 4), Integer.valueOf(2));
    
            // doAnswer
            Mockito.doAnswer(invocationOnMock -> myAbc.offset = 0).when(myAbc).initOffset(4);
            myAbc.initOffset(4);
            Assert.assertEquals(myAbc.offset, Integer.valueOf(0));
    
            // thenThrow
            Mockito.when(myAbc.div(ArgumentMatchers.eq(2), ArgumentMatchers.eq(0))).thenThrow(new ArithmeticException());
            try {
                myAbc.div(2, 0);
                Assert.fail();
            } catch (ArithmeticException e) {
                // expected exception
            }
    
            // doThrow
            Mockito.doThrow(new IllegalStateException()).when(myAbc).initOffset(3);
            try {
                myAbc.initOffset(3);
                Assert.fail();
            } catch (IllegalStateException e) {
                // expected exception
            }
        }
    }
  3. TemporaryFolder: saving/reading data to/from files, copying files
    src/test/resources/abc.txt:
    Hello 'abc.txt' content!!!
    src/test/java/mtitek/junit/samples/TemporaryFolderTest.java:
    package mtitek.junit.samples;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.file.Files;
    import java.nio.file.StandardCopyOption;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.io.IOUtils;
    import org.junit.Assert;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.TemporaryFolder;
    
    public class TemporaryFolderTest {
        @Rule
        public TemporaryFolder temporaryFolder = new TemporaryFolder();
    
        @Test
        public void testTemporaryFolder() throws IOException {
            File createdFolder = temporaryFolder.newFolder("subfolder");
            File createdFile = temporaryFolder.newFile("myfile.txt");
    
            System.out.println(createdFolder);
            System.out.println(createdFile);
        }
    
        // saving/reading data to/from files
        @Test
        public void test() throws IOException {
            final File newFile = temporaryFolder.newFile();
            System.out.println("newFile: " + newFile);
    
            final String data = "foo";
    
            try (final FileOutputStream fileOutputStream = new FileOutputStream(newFile)) {
                IOUtils.copy(IOUtils.toInputStream(data, "UTF-8"), fileOutputStream);
            }
    
            try (final InputStream inputStream = new FileInputStream(newFile)) {
                Assert.assertEquals(data, IOUtils.toString(inputStream, "UTF-8"));
            }
        }
    
        // copying files
        @Test
        public void testFiles() throws IOException {
            File createdFile = temporaryFolder.newFile("abc-copy.txt");
    
            try (final InputStream input = ClassLoader.getSystemResourceAsStream("abc.txt")) {
                Files.copy(input, createdFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
    
            Assert.assertEquals("Hello 'abc.txt' content!!!", FileUtils.readFileToString(createdFile, "UTF-8"));
    
            final String body = FileUtils.readFileToString(createdFile, "UTF-8");
            System.out.println(createdFile.toPath());
            System.out.println(body);
        }
    }
  4. WireMock: testing an HttpGet request
    src/test/java/mtitek/junit/samples/WireMockTest.java:
    package mtitek.junit.samples;
    
    import java.io.IOException;
    
    import org.apache.commons.io.IOUtils;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.junit.Assert;
    import org.junit.Rule;
    import org.junit.Test;
    
    import com.github.tomakehurst.wiremock.client.WireMock;
    import com.github.tomakehurst.wiremock.junit.WireMockRule;
    
    public class WireMockTest {
        @Rule
        public WireMockRule wireMockRule = new WireMockRule(8880);
    
        @Test
        public void testWireMock() throws IOException {
            WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/abc/xyz"))
                    .willReturn(WireMock.aResponse().withStatus(HttpStatus.SC_OK).withBody("Hello WireMock!!!")));
    
            final HttpGet httpGet = new HttpGet("http://localhost:8880/abc/xyz");
    
            try (CloseableHttpClient httpClient = HttpClients.custom().build();
                    final CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
                WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/abc/xyz")));
    
                Assert.assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine().getStatusCode());
    
                final HttpEntity entity = httpResponse.getEntity();
    
                Assert.assertEquals("Hello WireMock!!!", IOUtils.toString(entity.getContent(), "UTF-8"));
    
                // close the content stream.
                EntityUtils.consumeQuietly(entity);
            }
        }
    }
© 2025  mtitek