반응형

AssertionTests

import org.hamcrest.core.CombinableMatcher;
import org.junit.Test;

import java.util.Arrays;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public class AssertTests {
    @Test
    public void testAssertArrayEquals() {
        byte[] expected = "trial".getBytes();
        byte[] actual = "trial".getBytes();
        assertArrayEquals("failure - byte arrays not same", expected, actual);
    }

    @Test
    public void testAssertEquals() {
        assertEquals("failure - strings are not equal", "text", "text");
    }

    @Test
    public void testAssertFalse() {
        assertFalse("failure - should be false", false);
    }

    @Test
    public void testAssertNotNull() {
        assertNotNull("should not be null", new Object());
    }

    @Test
    public void testAssertNotSame() {
        assertNotSame("should not be same Object", new Object(), new Object());
    }

    @Test
    public void testAssertNull() {
        assertNull("should be null", null);
    }

    @Test
    public void testAssertSame() {
        Integer aNumber = Integer.valueOf(768);
        assertSame("should be same", aNumber, aNumber);
    }

    // JUnit Matchers assertThat
    @Test
    public void testAssertThatBothContainsString() {
        assertThat("albumen", both(containsString("a")).and(containsString("b")));
    }

    @Test
    public void testAssertThatHasItems() {
        assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));
    }

    @Test
    public void testAssertThatEveryItemContainsString() {
        assertThat(Arrays.asList(new String[]{"fun", "ban", "net"}), everyItem(containsString("n")));
    }

    // Core Hamcrest Matchers with assertThat
    @Test
    public void testAssertThatHamcrestCoreMatchers() {
        assertThat("good", allOf(equalTo("good"), startsWith("good")));
        assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));
        assertThat("good", anyOf(equalTo("bad"), equalTo("good")));
        assertThat(7, not(CombinableMatcher.either(equalTo(3)).or(equalTo(4))));
        assertThat(new Object(), not(sameInstance(new Object())));
    }

    @Test
    public void testAssertTrue() {
        assertTrue("failure - should be true", true);
    }
}

TestFixturesExample

import org.junit.*;

public class TestFixturesExample {
    @BeforeClass
    public static void setUpClass() {
        System.out.println("@BeforeClass");
    }

    @AfterClass
    public static void tearDownClass() {
        System.out.println("@AfterClass");
    }

    @Before
    public void setUp() {
        System.out.println("@Before");
    }

    @After
    public void tearDown() {
        System.out.println("@After");
    }

    @Test
    public void test1() {
        System.out.println("test1");
    }

    @Test
    public void test2() {
        System.out.println("test2");
    }
}

IgnoreTests

import org.junit.Ignore;
import org.junit.Test;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class IgnoreTests {
    @Ignore("Test is ignored as a demonstration")
    @Test
    public void testSame() {
        assertThat(1, is(1));
    }
}

ExceptionTests

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;

public class ExceptionTests {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testExceptionAndState() {
        List<Object> list = new ArrayList<>();

        // version - 4.13
        IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> list.add(1, new Object()));

        // assertions on the thrown exception
        assertEquals("Index: 1, Size: 0", thrown.getMessage());
        // assertions on the state of a domain object after the exception has been thrown
        assertTrue(list.isEmpty());
    }

    @Test
    public void testExceptionMessage() {
        List<Object> list = new ArrayList<>();

        try {
            list.get(0);
            fail("Expected an IndexOutOfBoundsException to be thrown");
        } catch (IndexOutOfBoundsException e) {
            assertThat(e.getMessage(), is("Index 0 out of bounds for length 0"));
        }
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void empty() {
        new ArrayList<>().get(0);
    }

    @Test
    public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {
        List<Object> list = new ArrayList<>();

        thrown.expect(IndexOutOfBoundsException.class);
        thrown.expectMessage("Index 0 out of bounds for length 0");
        list.get(0); // execution will never get past this line
    }
}

TimeoutTests

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class TimeoutTests {
    @Rule
    public Timeout globalTimeout = Timeout.seconds(10); // 10 seconds max per method tested

    @Test
    public void testSleepForTooLong() throws Exception {
        TimeUnit.SECONDS.sleep(100); // sleep for 100 seconds
    }

    @Test
    public void testBlockForever() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        latch.await(); // will block
    }

    @Test(timeout = 1000)
    public void testWithTimeout() throws InterruptedException {
        TimeUnit.SECONDS.sleep(100); // sleep for 100 seconds
    }
}

ParameterizedTests

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class ParameterizedTests {
    @Parameterized.Parameters
    public static Collection<Object[]> parameters() {
        return Arrays.asList(new Object[][]{
            {0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}
        });
    }

    private int input;
    private int expected;

    public ParameterizedTests(int input, int expected) {
        this.input = input;
        this.expected = expected;
    }

    @Test
    public void test() {
        assertEquals(expected, fibonacci(input));
    }

    public static int fibonacci(int n) {
        return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
    }
}

MultiThreadTests

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.junit.Assert.assertTrue;

public class MultiThreadTests {
    @Test
    public void testMultiThreads() {
        List<Runnable> runnableList = Arrays.asList(
            () -> System.out.println("Hello World - 1"),
            () -> System.out.println("Hello World - 2"),
            () -> System.out.println("Hello World - 3"),
            // () -> System.out.println(10 / 0), // for exception test
            () -> System.out.println("Hello World - 4")
        );

        ExecutorService service = Executors.newFixedThreadPool(runnableList.size());
        List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>());

        try {
            for (Runnable runnable : runnableList) {
                service.submit(() -> {
                    try {
                        runnable.run();
                    } catch (Exception e) {
                        exceptions.add(e);
                    }
                });
            }
        } finally {
            service.shutdownNow();
        }

        assertTrue("failed with exception(s)" + exceptions, exceptions.isEmpty());
        System.out.println("finish");
    }
}

TempFolderTests

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.IOException;

import static org.junit.Assert.assertTrue;

public class TempFolderTests {
    @Rule
    public final TemporaryFolder tempFolder = new TemporaryFolder();

    @Test
    public void test() throws IOException {
        File icon = tempFolder.newFile("icon.png");
        File assets = tempFolder.newFolder("assets");

        assertTrue(icon.exists());
        assertTrue(assets.exists());
    }
}

TestMethodOrder

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.OrderWith;
import org.junit.runner.manipulation.Alphanumeric;
import org.junit.runners.MethodSorters;

@OrderWith(Alphanumeric.class)
//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestMethodOrder {
    @Test
    public void testC() {
        System.out.println("third");
    }

    @Test
    public void testB() {
        System.out.println("second");
    }

    @Test
    public void testA() {
        System.out.println("first");
    }
}
반응형

'Development > Java' 카테고리의 다른 글

[Java] Singleton Pattern  (0) 2022.01.07
[Java] JUnit5  (0) 2021.12.08
[Java] Hash Algorithm  (0) 2021.11.17
[Java] Stream  (0) 2021.09.09
[Java] Shell Command 실행하기  (0) 2021.08.28

+ Recent posts