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.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
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 findByName() {
try {
EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
PowerMockito.whenNew(EmployeeDao.class).withAnyArguments().thenReturn(employeeDao);
EmployeeService employeeService = new EmployeeService();
PowerMockito.when(employeeDao.findByName("andy")).thenReturn("haha");
String result = employeeService.find("andy");
Assert.assertEquals("haha", result);
PowerMockito.when(employeeDao.findByName("Tom")).thenReturn("haha");
String result2 = employeeService.find("Tom");
Assert.assertEquals("haha", result2);
} catch (Exception e) {
Assert.fail();
}
}
/**
* 使用Matcher
*/
@Test
public void findByNameWithMatcher() {
try {
EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
PowerMockito.whenNew(EmployeeDao.class).withAnyArguments().thenReturn(employeeDao);
PowerMockito.when(employeeDao.findByName(ArgumentMatchers.argThat(new MyArgumentMatcher()))).thenReturn("hehe");
EmployeeService employeeService = new EmployeeService();
Assert.assertEquals("hehe",employeeService.find("Tom"));
Assert.assertEquals("hehe",employeeService.find("Andy"));
Assert.assertEquals("hehe",employeeService.find("Tony"));
// Assert.assertEquals("hehe",employeeService.find("Boss"));
} catch (Exception e) {
Assert.fail();
}
}
static class MyArgumentMatcher implements ArgumentMatcher<String> {
public boolean matches(String argument) {
switch (argument) {
case "Tom":
case "Andy":
case "Tony":
return true;
default:
return false;
}
}
}
}