import lombok.Data;
/**
* @author chenjianfei
*/
@Data
public class Employee {
private String name;
private Integer age;
}
public class EmployeeDao {
public String findByName(String name) {
throw new UnsupportedOperationException();
}
}
public class EmployeeService {
public String find(String name) {
EmployeeDao employeeDao = new EmployeeDao();
return employeeDao.findByName(name);
}
}
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(EmployeeService.class)
public class EmployeeServiceTest {
@Test
public void findByNameWithAnswer() {
try {
EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
PowerMockito.whenNew(EmployeeDao.class).withAnyArguments().thenReturn(employeeDao);
PowerMockito.when(employeeDao.findByName(Mockito.anyString())).then(invocation -> {
String args = (String) invocation.getArguments()[0];
switch (args) {
case "Jacky":
return "I am Jacky";
case "Andy":
return "I am Andy";
default:
throw new RuntimeException("Not Support:" + args);
}
});
EmployeeService employeeService = new EmployeeService();
Assert.assertEquals("I am Jacky",employeeService.find("Jacky"));
Assert.assertEquals("I am Andy",employeeService.find("Andy"));
try{
String anyValue = employeeService.find("anyValue");
Assert.fail();
}catch (Exception e){
Assert.assertTrue(e instanceof RuntimeException);
}
} catch (Exception e) {
Assert.fail();
}
}
}