Home > OS >  How To Write a Java Unit Test for the Method inside Another Method?
How To Write a Java Unit Test for the Method inside Another Method?

Time:08-13

 Public Class DailyJob(){

   public void runJob(ScheduleJob currentJob) {
    
    try {
            int employee = employeeService.getEmployeeNum();
            JobPerformance jobPerformance = performanceService.searchJobPerformance(employee);
            if(jobPerformance.size() >0 ) {
                currentJob.setRecord("success");
           }
            else {
                currentJob.setRecord("failed");
                }
    }
    catch{
    //catch error
         }
      }
  }

By now I want to write a Junit test for runJob(). But how can I setup the value I prefer into 'employee' parameter in Junit Test while I test runJob()? Anyone know how to implement it?

CodePudding user response:

You can use Mockito. You setup stubbing, which will return desired value. Also you can stub for multiple calls by

.thenReturn(9, 10, 7);
import org.junit.jupiter.api.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;


public class MyTest {

    @Test
    void test() {
        EmployeeService employeeService = mock(EmployeeService.class);
        when(employeeService.getEmployeeNum()).thenReturn(9);
       
    }
}
  • Related