In: Computer Science
write the program in java.
Demonstrate that you understand how to use create a class and test it using JUnit
Let’s create a new Project HoursWorked
Under your src folder, create package edu.cincinnatistate.pay
Now, create a new class HoursWorked in package edu.cincinnatistate.pay
This class needs to do the following:
Have a constructor that receives intHours which will be stored in totalHrs
Have a method addHours to add hours to totalHrs
Have a method subHours to subtract hours from totalHrs
Have a method that returns the totalHrs
This class must have JavaDoc comments above the class name and above every method.
Once you create the HoursWorked class, a Junit Test HoursWorkedTest.
This should use @BeforeEach to setup the default HoursWorked to 8 hours.
Create @Test testAddHours to test adding hours
Create @test testSubHours to test subtracting hours
Be sure to generate an error in your test and provide comments on why this is an error
Java Code:
package edu.cincinnatistate.pay;
/**
* Class to store the number of hours worked
* Contains method to add and subtract hours
* Has a constructor to populate initial value
*/
public class HoursWorked {
private int totalHrs;
/**
* Constructor to initialize total hours
* @return none
* @param int hours
*/
public HoursWorked(int hours) {
totalHrs = hours;
}
/**
* Adds the hours
* @return void
* @param int hours
*/
public void addHours (int hours) {
totalHrs += hours;
}
/**
* Subtract the hours
* @return void
* @param int hours
*/
public void subHours (int hours) {
totalHrs -= hours;
}
/**
* Returns the total hours
* @return int total hours
*/
public int returnTotalHours() {
return totalHrs;
}
}
JUnit Code:
package edu.cincinnatistate.pay;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class HoursWorkedTest {
int defaultHoursWorked; //to store default hours
worked
@BeforeEach
void setupMethod() {
defaultHoursWorked = 8;
}
//positive test case for add hours
@Test
void testAddHours() {
HoursWorked hwObj = new
HoursWorked(defaultHoursWorked);
hwObj.addHours(5);
assertEquals(hwObj.returnTotalHours(), 13, "Hours are not
equal");
}
//positive test case for subtract hours
@Test
void testSubHours() {
HoursWorked hwObj = new
HoursWorked(defaultHoursWorked);
hwObj.subHours(5);
assertEquals(hwObj.returnTotalHours(), 3, "Hours are not
equal");
}
//negative test case for subtract hours
@Test
void testSubHoursError() {
HoursWorked hwObj = new
HoursWorked(defaultHoursWorked);
hwObj.subHours(5);
//8-5 will result in 3 but we are
checking for 8 so this will throw an error
assertEquals(hwObj.returnTotalHours(), 8, "Error case");
}
}
Sample Output: