使用 mockito 进行 Unitest(一个 class 依赖于其他场景)

Unitest by using mockito(one class is dependent with other scenario)

您好,我是模拟框架的新手。任何人都可以帮助我使用任何模拟框架编写 junit 。以下是我的要求

我想通过使用具有预期值的模拟为 getListOfEmp 方法编写一个单元测试。

注意 在这里,我很难模拟 EmpValue class 以获得 ServiceClass

中的准确值
 public class ServiceClass {
    public Employe getListOfEmp(List<String> criteria) {
    Employe emp = new Employe();
    EmpValue empValue = new EmpValue();

    if (criteria.contains("IT")) {
        emp.setEid(empValue.getIt());
    }
    if (criteria.contains("SALES")) {
        emp.setEid(empValue.getSales());
    }
    if (criteria.contains("SERVICE")) {
        emp.setEid(empValue.getService());
    }
    return emp;
   }
}


public class EmpValue {
    private String it = "IT-1001";
    private String service = "SERVICE-1001";
    private String sales = "SALES-1001";
    public String getIt() {
       return it;
    }
    public String getService() {
        return service;
    } 
    public String getSales() {
       return sales;
    }
  }

首先,我将对代码进行一些更改以使其可测试。

1: EmplValue 对象应该由客户端传递给方法,或者应该是您服务中的一个实例变量class。这里我将它作为一个实例变量来使用,以便客户端可以设置它。

public class ServiceClass {
    private EmpValue empValue;

    public ServiceClass(EmpValue empValue){
        this.empValue = empValue;
    }

    public Employe getListOfEmp(List<String> criteria) {
        Employe emp = new Employe();

        if (criteria.contains("IT")) {
            emp.setEid(empValue.getIt());
        }
        if (criteria.contains("SALES")) {
            emp.setEid(empValue.getSales());
        }
        if (criteria.contains("SERVICE")) {
            emp.setEid(empValue.getService());
        }
        return emp;
    }
}

我正在使用 Mockito 和 JUnit 为此 class 编写单元测试。

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunsWith(MockitoJunitRunner.class)
public class ServiceClassTest{

@Test  
public void shouldReturnEmployeeWithEidSetWhenCriteriaIsIT(){
   // Craete mock and define its behaviour
   EmpValue mEmpValue = mock(EmpValue.class);
   when(mEmpValue.getIt()).thenReturn("IT-1001");

  // Create the object of class user test with mock agent and invoke
   ServiceClass serviceClass = new ServiceClass(mEnpValue);
   Employee result = serviceClass.getListOfEmp(asList("IT"));

   // Verify the result as per your expectation
   assertEquals("It-001", result.getEid());
}

}