Pick a Java method from Simple2.java and write a single JUnit test for it. Do not test all scenarios for the method but a single scenario in a single test.

 

Pick a Java method from Simple2.java and write a single JUnit test for it. Do not test all scenarios for the method but a single scenario in a single test.

 

Go over unit test in general and JUnit in particular. A good way to start with JUnit is the following tutorial with examples of JUnit tests: http://java.dzone.com/articles/junit-tutorial-beginners.

 

Reply with your unit tests….

Review the below example first:

Example:

Note 1: first test that attributes are being assigned correctly accessing the fields directly using default constructor
Note 2: Make sure that test names are meaningful and that you only test a single attribute or value
Note 3: Once you test the attributes are set correctly, you can test using get method

@Test

/*

* Test Example 1

* Test that default constructor assigns value 1 to num1

*  uses import java.lang.reflect.Field;

*/

public void testDefaultSimple2AttributeNum1()

{

Simple sc = new Simple2();   // create an instance of class Simple2

try {

Class s2Class = sc.getClass();  // get class information

Field f1;

f1 = s2Class.getDeclaredField(“num1”);  // get attribute value1

f1.setAccessible(true);  // allow attribute to be accessed

int value = (int)f1.get(sc);  // get the value of attribute and cast to the data type it is

assertEquals(1, value);  // compare values

 

} catch (NoSuchFieldException e) {

fail(“Code issue: Expected Simple2 to have attribute num1 and it is missing”);

} catch (SecurityException e) {

fail(“Test issue: Access denied to the fields in the class Simple2”);

} catch (IllegalArgumentException e) {

fail(“Test issue: the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).”);

} catch (IllegalAccessException e) {

fail(“Test issue: Field object is enforcing Java language access control and the underlying field is inaccessible.”);

}

}

@Test

/*

* Test that getNum1 returns value 1 for num1

* Test Example 2

*/

public void testDefaultSimple2GetNum1()

{

Simple sc = new Simple2();   // create an instance of class Simple2

assertEquals(1, sc.getNum1());

}

 

Order Now