Unit testing
From this post, I will explain basic of automated testing.In this post, I will show you very very basic of unit testing using JUnit.
We use YahooExchangeRateApi as testing target code introduced in http://dukesoftware00.blogspot.com/2013/10/java-get-exchange-rate-from-yahoo.html.
Unit Test class & Annotaions
The first of first, write simple unit testing code for YahooExchangeRateApi class. A few things you should remenber:- Add @Test annotation to test method.
- Use @BeforeClass for execute something *once* before actual all tests defined in the test class.
- Use @Before for execute something before actual *each* tests defined in the test class.
- Use @AfterClass and @After are simply opposite meaning of @BeforeClass and @Before. e.g. executed after test methods.
- You can test exception thrown by @Test(expected=Exception.class)
Yeah that's all! Let's see the actual test class code....
package com.dukesoftware.exchangerate.api; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.dukesoftware.exchangerate.api.Rate; import com.dukesoftware.exchangerate.api.YahooExchangeRateApi; public class YahooCurrencyRateApiTest { private static YahooExchangeRateApi API; @BeforeClass public static void setUp() { System.out.println(" Before all tests"); API = new YahooExchangeRateApi(); } @AfterClass public static void tearDown() { System.out.println(" After all tests"); API = null; } @Before public void before() { System.out.println(" Before test"); } @After public void after() { System.out.println(" After test\n"); } // normal case @Test public void testGetRateSuccess() { System.out.println(" test1"); // execute Rate rate = API.getRate("USD", "JPY"); // check assertEquals("USD", rate.getCcy1()); assertEquals("JPY", rate.getCcy2()); assertTrue(rate.getValue() > 0); assertNotNull(rate.getDate()); System.out.println(" " + rate); } // exception test @Test(expected=IllegalArgumentException.class) public void expectExceptionForGetRate_NullCcy1() { System.out.println(" test2"); API.getRate(null, "JPY"); } }
Unit Testing Reference
If you would like to know about unit testing more, read following refence for software testing. I highly recommends this book.This book is really practical and make clear the terms in testing. If you would like to know the difference between "mock" and "stub", you should read this :)
コメント