001/** 002 * This is part of HW0: Environment Setup and Java Introduction for CSE 331. 003 */ 004package hw3.test; 005import hw3.*; 006 007import org.junit.Test; 008import org.junit.BeforeClass; 009import static org.junit.Assert.*; 010 011/** 012 * FibonacciTest is a glassbox test of the Fibonacci class. 013 * 014 * Recall that the Fibonacci sequence is a recursive 015 * sequence where the first two terms of the sequence are 1 and all subsequent 016 * terms are the sum of the previous two terms. 017 * 018 * Thus, the Fibonacci sequence starts out as 1, 1, 2, 3, 5, 8, 13... 019 * The first 1 in the sequence is considered the "0th" term, 020 * so the indices that <code>hw3.Fibonacci</code> uses are 0-based. 021 * 022 * @see hw3.Fibonacci 023 * 024 * @author mbolin 025 */ 026public class FibonacciTest { 027 028 private static Fibonacci fib = null; 029 030 @BeforeClass 031 public static void setupBeforeTests() throws Exception { 032 fib = new Fibonacci(); 033 } 034 035 /** 036 * Tests that Fibonacci throws an IllegalArgumentException 037 * for a negative number. 038 */ 039 @Test(expected=IllegalArgumentException.class) 040 public void expectedIllegalArgumentException() { 041 fib.getFibTerm(-1); 042 } 043 044 045 /** 046 * Tests that Fibonacci throws no IllegalArgumentException 047 * for zero or for a positive number. 048 */ 049 @Test 050 public void testThrowsIllegalArgumentException() { 051 052 // test 0 053 try { 054 fib.getFibTerm(0); 055 } catch (IllegalArgumentException ex) { 056 fail("Threw IllegalArgumentException for 0 but 0 is nonnegative: " 057 + ex); 058 } 059 060 // test 1 061 try { 062 fib.getFibTerm(1); 063 } catch (IllegalArgumentException ex) { 064 fail("Threw IllegalArgumentException for 1 but 1 is nonnegative: " 065 + ex); 066 } 067 } 068 069 /** Tests to see that Fibonacci returns the correct value for the base cases, n=0 and n=1 */ 070 @Test 071 public void testBaseCase() { 072 assertEquals("getFibTerm(0)", 1, fib.getFibTerm(0)); 073 assertEquals("getFibTerm(1)", 1, fib.getFibTerm(1)); 074 } 075 076 /** Tests inductive cases of the Fibonacci sequence */ 077 @Test 078 public void testInductiveCase() { 079 int[][] cases = new int[][] { 080 { 2, 2 }, 081 { 3, 3 }, 082 { 4, 5 }, 083 { 5, 8 }, 084 { 6, 13 }, 085 { 7, 21 } 086 }; 087 for (int i = 0; i < cases.length; i++) { 088 assertEquals("getFibTerm(" + cases[i][0] + ")", 089 cases[i][1], fib.getFibTerm(cases[i][0])); 090 } 091 } 092 093}