JUnit基本用法

0x00 引言

JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,很多开发工具都集成了对JUnit的支持,就像支持Git一样。使用JUnit做测试是一种白盒测试。JUnit作为一个测试框架,使用JUnit3的时候需要继承TestCase类,JUnit4不需要继承它。自己做测试以前使用都是使用main,不管是简单的printf、alert,还是复杂的debug,感觉都没有JUnit方便。Python中有基于JUnit的衍生版本。C系列Google出的很好用。C语言cmocka很不错。

0x01 示例

file: CompareStrings.java

    /**
     * Created by Guile on 2015-4-4.
     */

    public class CompareStrings {
        /**
         * @param A : A string includes Upper Case letters
         * @param B : A string includes Upper Case letter
         * @return :  if string A contains all of the characters in B return true else return false
         */
        public boolean compareStrings(String A, String B) {
            // write your code here
            //
            if (0 == B.length()) {
                return true;
            }

            int[] temp = new int[26];

            for (int i = 0; i < A.length(); i++) {
                char c = A.charAt(i);
                temp[c - 'A'] += 1;
            }

            for (int i = 0; i < B.length(); i++) {
                char c = B.charAt(i);
                temp[c - 'A'] -= 1;
                if (temp[c - 'A'] < 0) {
                    return false;
                }
            }
            return true;
        }
    }

file: CompareStringsTest.java

    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;

    import static org.junit.Assert.*;

    /**
     * Created by Guile on 2015-4-4.
     */
    public class CompareStringsTest {
        private CompareStrings compare;

        @Before
        public void setUp() throws Exception {
            compare = new CompareStrings();
            System.out.printf("@Before \n");

        }

        @After
        public void tearDown() throws Exception {
            System.out.printf("@After \n");

        }

        @Test
        public void testCompareStrings() throws Exception {
            System.out.printf("now ! Testing \n");
            assertEquals(true, compare.compareStrings("ABC","AB"));
            assertEquals(false, compare.compareStrings("ABC","ABD"));
            assertEquals(false, compare.compareStrings("ABCDEFG", "ACC"));
            assertEquals(true, compare.compareStrings("ABCDEFG", "AC"));

        }
    }

你可能感兴趣的:(JUnit基本用法)