CodeTime: Testing AK47 with JUnit.

JUnit

Reference: http://www.jetbrains.com/idea/webhelp/configuring-testing-libraries.html

JUnit is a testing framework for Java as far as I know, and I use it for the first time. After some research on google, now I know that JUnit comes with intelliJ IDEA. I'm using intelliJ, so try it. Basically what you have to do to make the test code is highlighting the class you want to test and press ⌘(CTRL) + Shift + T. Boom! Dialog will soon pop up.

f:id:sumioturk:20120830233434p:plain

Click OK to generate test class. Now let's make some test and see how it works.

Here is the AK47 I will test with JUnit ... For the sake of ease of test, I leave ammo and safety as public properties.

package models.guns;

public class AK47 implements Firearm {

    public final String cartridge = "7.62x39mm M43/M67";
    public Integer ammo = 20;
    public Boolean safety = false;

    public void shoot(){
        if(ammo == 1){
            reload();
        }else{
            ammo--;
        }
    }

    public void reload(){
        ammo = 20;
    }

    public Boolean isSafetyOn(){
        return safety;
    }

    public void switchSafety(){
        safety = !safety;
    }

}

Now initiate the dialog with ⌘(CTRL) + Shift + T. Check all the methods you want to test. This will automatically generates the scheme for ya. FYI, sometimes it generates some lines that you don't want. If you don't like such behavior, then just leave all the methods unchecked.
f:id:sumioturk:20120830235712p:plain


package models;

import junit.framework.TestCase;
import org.testng.annotations.Test;

public class AK47Test extends TestCase{
    @Test
    public void testShoot() throws Exception {

        AK47 ak47 = new AK47();
        assertEquals(ak47.cartridge, "7.62x39mm M43/M67");

        ak47.shoot();
        assertSame(20 - 1, ak47.ammo);

    }

    public void testReload() throws Exception {

        AK47 ak47 = new AK47();
        for(int i = 0; i < 20; i++){
            ak47.shoot();
        }
        assertSame(20, ak47.ammo);

        ak47.reload();
        assertSame(19 + 1, ak47.ammo);
    }

    public void testIsSafetyOn() throws Exception {

        AK47 ak47 = new AK47();
        assertSame(false, ak47.isSafetyOn());

    }

    public void testSwitchSafety() throws Exception {

        AK47 ak47 = new AK47();
        ak47.switchSafety();
        assertSame(true, ak47.isSafetyOn());

    }
}

Tests all passed. Seems my AK47 is in good condition. Let's lock n load.

f:id:sumioturk:20120831002100p:plain