Exercise 1:
1. //The max function the max between a and b, it returns a if a == //b
public double max(double a, double b);
2. //The mult function returns the result of a * b public double mult(double a, double b);
3. //The exist in array function returns the index of the element //‘a’ if //‘a’ exist in array ‘arr’ otherwise returns ‘-1’ public int existsInArray(int [] arr, int a);
4. //Are array equals method compares two arrays and returns true // if the elements of array ‘a’ are equal to elements of array
// ‘b’, element by element. If equals it returns 0, it returns -
// 1 if not
public int areArrayEquals(int [] a, int [] b);
Devise four executable test cases for every method in the JUnit notation. See the attached handout for a refresher on the notation.
import static org.junit.Assert.*;
import org.junit.*;
class Function {
/**
* The max function the max between a and b, it returns a if a == //b
*
* @param a
* @param b
* @return
*/
public double max(double a, double b) {
if (a >= b) {
return a;
}
return b;
}
/**
* The mult function returns the result of a * b
*
* @param a
* @param b
* @return
*/
public double mult(double a, double b) {
return a * b;
}
/**
* The exist in array function returns the index of the element //‘a’ if //‘a’
* exist in array ‘arr’ otherwise returns ‘-1’
*
* @param arr
* @param a
* @return
*/
public int existsInArray(int[] arr, int a) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == a) {
return i;
}
}
return -1;
}
/***
* Are array equals method compares two arrays and returns true // if the
* elements of array ‘a’ are equal to elements of array ‘b’, element by element.
* If equals it returns 0, it returns - 1 if not
*
* @param a
* @param b
* @return
*/
public int areArrayEquals(int[] a, int[] b) {
if (a.length <= b.length) {
return -1;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return -1;
}
}
return 0;
}
}
public class JFunctionsTest {
private Function function;
@Before
public void setUp() {
function=new Function();
}
@Test
public void testMax() {
double a = 25.0;
double b = 56.0;
double actual = function.max(a, b);
double expected = 56.0;
assertTrue(expected==actual);
}
@Test
public void testMult() {
double a = 2.0;
double b = 10.0;
double actual = function.mult(a, b);
double expected = 20.0;
assertTrue(expected==actual);
}
@Test
public void testExistsInArray() {
int a = 2;
int array[] = { 10,2,56,36,95};
int actual = function.existsInArray(array, a);
int expected =1;
assertTrue(expected==actual);
}
@Test
public void testAreArrayEquals() {
int a[] = { 10,2,56,36,95};
int b[] = { 14,2,56,36,95};
int actual = function.areArrayEquals(a, b);
int expected =-1;
assertTrue(expected==actual);
}
}
Comments
Leave a comment