Unitest使用mockito(一个类依赖于其他场景)

时间:2015-05-07 18:47:11

标签: tdd

嗨,我是嘲笑框架的新手。任何人都可以帮我写一个junit使用任何模拟框架。以下是我的要求

我想通过使用具有预期值的mock来为getListOfEmp方法编写一个unitest。

注意我在模拟EmpValue课程时难以获得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 个答案:

答案 0 :(得分:0)

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

1:EmplValue对象应该由客户端传递给方法,或者应该是Service类中的实例变量。这里我将它用作实例变量,以便客户端可以设置它。

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为这个类编写单元测试。

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());
}

}