<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
public class ListTest {
@Test
public void testSize() {
Integer expected = 100;
List list = PowerMockito.mock(List.class);
PowerMockito.when(list.size()).thenReturn(expected);
Integer actual = list.size();
Assert.assertEquals("返回值不相等", expected, actual);
}
}
声明:
T PowerMockito.mock(Class clazz);
@RunWith(PowerMockRunner.class)
@PrepareForTest({TargetClass.class})
public class Rectangle implements Sharp {
private double width;
private double height;
public double getArea() {
return width * height;
}
}
public class RectangleTest {
public void testGetArea() {
double expectArea = 100.0D;
Rectangle rectangle = PowerMockito.mock(Rectangle.class);
PowerMockito.when(rectangle.getArea()).thenReturn(expectArea);
double actualArea = rectangle.getArea();
Assert.assertEquals("返回值不相等", expectArea, actualArea, 1E-6D);
}
}
public final class Circle {
private double radius;
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
}
(PowerMockRunner.class)
({Circle.class})
public class CircleTest {
public void testGetArea() {
double expectArea = 3.14D;
Circle circle = PowerMockito.mock(Circle.class);
PowerMockito.when(circle.getArea()).thenReturn(expectArea);
double actualArea = circle.getArea();
Assert.assertEquals("返回值不相等", expectArea, actualArea, 1E-6D);
}
}
PowerMockito.mockStatic(Class clazz);
(PowerMockRunner.class)
({StringUtils.class})
public class StringUtilsTest {
public void testIsEmpty() {
String string = "abc";
boolean expected = true;
PowerMockito.mockStatic(StringUtils.class);
PowerMockito.when(StringUtils.isEmpty(string)).thenReturn(expected);
boolean actual = StringUtils.isEmpty(string);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
PowerMockito.spy(Class clazz);
public class StringUtils {
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
}
(PowerMockRunner.class)
({StringUtils.class})
public class StringUtilsTest {
public void testIsNotEmpty() {
String string = null;
boolean expected = true;
PowerMockito.spy(StringUtils.class);
PowerMockito.when(StringUtils.isEmpty(string)).thenReturn(!expected);
boolean actual = StringUtils.isNotEmpty(string);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
T PowerMockito.spy(T object);
public class StringUtils {
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
}
(PowerMockRunner.class)
({StringUtils.class})
public class StringUtilsTest {
public void testIsNotEmpty() {
String string = null;
boolean expected = true;
PowerMockito.spy(StringUtils.class);
PowerMockito.when(StringUtils.isEmpty(string)).thenReturn(!expected);
boolean actual = StringUtils.isNotEmpty(string);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
PowerMockito.when(mockObject.someMethod(someArgs)).thenReturn(expectedValue);
PowerMockito.when(mockObject.someMethod(someArgs)).thenThrow(expectedThrowable);
PowerMockito.when(mockObject.someMethod(someArgs)).thenAnswer(expectedAnswer);
PowerMockito.when(mockObject.someMethod(someArgs)).thenCallRealMethod();
public class ListTest {
public void testGet() {
int index = 0;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.when(mockList.get(index)).thenReturn(expected);
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
public void testGet() {
int index = -1;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.when(mockList.get(index)).thenThrow(new IndexOutOfBoundsException());
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
public void testGet() {
int index = 1;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.when(mockList.get(index)).thenAnswer(invocation -> {
Integer value = invocation.getArgument(0);
return value * 100;
});
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
@Test
public void testGet() {
int index = 0;
Integer expected = 100;
List<Integer> oldList = new ArrayList<>();
oldList.add(expected);
List<Integer> spylist = PowerMockito.spy(oldList);
PowerMockito.when(spylist.get(index)).thenCallRealMethod();
Integer actual = spylist.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
PowerMockito.doReturn(expectedValue).when(mockObject).someMethod(someArgs);
PowerMockito.doThrow(expectedThrowable).when(mockObject).someMethod(someArgs);
PowerMockito.doAnswer(expectedAnswer).when(mockObject).someMethod(someArgs);
PowerMockito.doNothing().when(mockObject).someMethod(someArgs);
PowerMockito.doCallRealMethod().when(mockObject).someMethod(someArgs);
PowerMockito.doReturn(expectedValue).when(mockObject.someMethod(someArgs));
PowerMockito.doThrow(expectedThrowable).when(mockObject.someMethod(someArgs));
PowerMockito.doAnswer(expectedAnswer).when(mockObject.someMethod(someArgs));
PowerMockito.doNothing().when(mockObject.someMethod(someArgs));
PowerMockito.doCallRealMethod().when(mockObject.someMethod(someArgs));
public class ListTest {
public void testGet() {
int index = 0;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.doReturn(expected).when(mockList).get(index);
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
public void testGet() {
int index = -1;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.doThrow(new IndexOutOfBoundsException()).when(mockList).get(index);
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
public void testGet() {
int index = -1;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.doThrow(new IndexOutOfBoundsException()).when(mockList).get(index);
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
public void testGet() {
int index = 1;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.doAnswer(invocation -> {
Integer value = invocation.getArgument(0);
return value * 100;
}).when(mockList).get(index);
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
@Test
public void testGet() {
int index = 0;
Integer expected = 100;
List<Integer> oldList = new ArrayList<>();
oldList.add(expected);
List<Integer> spylist = PowerMockito.spy(oldList);
PowerMockito.doCallRealMethod().when(spylist).get(index);
Integer actual = spylist.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
4j
public class UserService {
public long getUserCount() {
log.info("调用获取用户数量方法");
return 0L;
}
}
public class UserServiceTest {
public void testGetUserCount() {
Long expected = 1000L;
UserService userService = PowerMockito.spy(new UserService());
PowerMockito.when(userService.getUserCount()).thenReturn(expected);
Long actual = userService.getUserCount();
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class UserServiceTest {
public void testGetUserCount() {
Long expected = 1000L;
UserService userService = PowerMockito.spy(new UserService());
PowerMockito.doReturn(expected).when(userService).getUserCount();
Long actual = userService.getUserCount();
Assert.assertEquals("返回值不相等", expected, actual);
}
}
PowerMockito.whenNew(MockClass.class).withNoArguments().thenReturn(expectedObject);
PowerMockito.whenNew(MockClass.class).withArguments(someArgs).thenReturn(expectedObject);
public final class FileUtils {
public static boolean isFile(String fileName) {
return new File(fileName).isFile();
}
}
(PowerMockRunner.class)
({FileUtils.class})
public class FileUtilsTest {
public void testIsFile() throws Exception {
String fileName = "test.txt";
File file = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withArguments(fileName).thenReturn(file);
PowerMockito.when(file.isFile()).thenReturn(true);
Assert.assertTrue("返回值为假", FileUtils.isFile(fileName));
}
}
public class ListTest {
public void testGet() {
int index = 1;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.when(mockList.get(Mockito.anyInt())).thenReturn(expected);
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
(PowerMockRunner.class)
({StringUtils.class})
public class StringUtilsTest {
public void testStartWith() {
String string = "abc";
String prefix = "b";
boolean expected = true;
PowerMockito.spy(StringUtils.class);
PowerMockito.when(StringUtils.startsWith(Mockito.anyString(), Mockito.eq(prefix))).thenReturn(expected);
boolean actual = StringUtils.startsWith(string, prefix);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class ListTest {
public void testGet() {
int index = 1;
Integer expected = 100;
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.when(mockList.get(AdditionalMatchers.geq(0))).thenReturn(expected);
PowerMockito.when(mockList.get(AdditionalMatchers.lt(0))).thenThrow(new IndexOutOfBoundsException());
Integer actual = mockList.get(index);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
Mockito.verify(mockObject[,times(int)]).someMethod(somgArgs);
public class ListTest {
public void testGet() {
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.doNothing().when(mockList).clear();
mockList.clear();
Mockito.verify(mockList).clear();
}
}
public class ListTest {
public void testGet() {
List<Integer> mockList = PowerMockito.mock(List.class);
PowerMockito.doNothing().when(mockList).clear();
mockList.clear();
Mockito.verify(mockList, Mockito.times(1)).clear();
}
}
public class ListTest {
@Test
public void testAdd() {
List<Integer> mockedList = PowerMockito.mock(List.class);
PowerMockito.doReturn(true).when(mockedList).add(Mockito.anyInt());
mockedList.add(1);
mockedList.add(2);
mockedList.add(3);
InOrder inOrder = Mockito.inOrder(mockedList);
inOrder.verify(mockedList).add(1);
inOrder.verify(mockedList).add(2);
inOrder.verify(mockedList).add(3);
}
}
public class ListTest {
@Test
public void testArgumentCaptor() {
Integer[] expecteds = new Integer[] {1, 2, 3};
List<Integer> mockedList = PowerMockito.mock(List.class);
PowerMockito.doReturn(true).when(mockedList).add(Mockito.anyInt());
for (Integer expected : expecteds) {
mockedList.add(expected);
}
ArgumentCaptor<Integer> argumentCaptor = ArgumentCaptor.forClass(Integer.class);
Mockito.verify(mockedList, Mockito.times(3)).add(argumentCaptor.capture());
Integer[] actuals = argumentCaptor.getAllValues().toArray(new Integer[0]);
Assert.assertArrayEquals("返回值不相等", expecteds, actuals);
}
}
public class ListTest {
public void testVerifyNoMoreInteractions() {
List<Integer> mockedList = PowerMockito.mock(List.class);
Mockito.verifyNoMoreInteractions(mockedList); // 执行正常
mockedList.isEmpty();
Mockito.verifyNoMoreInteractions(mockedList); // 抛出异常
}
}
public class StringUtilsTest {
public void testVerifyStatic() {
PowerMockito.mockStatic(StringUtils.class);
String expected = "abc";
StringUtils.isEmpty(expected);
PowerMockito.verifyStatic(StringUtils.class);
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
StringUtils.isEmpty(argumentCaptor.capture());
Assert.assertEquals("参数不相等", argumentCaptor.getValue(), expected);
}
}
public class UserService {
private Long userLimit;
public Long getUserLimit() {
return userLimit;
}
}
public class UserServiceTest {
private UserService userService;
public void testGetUserLimit() {
Long expected = 1000L;
ReflectionTestUtils.setField(userService, "userLimit", expected);
Long actual = userService.getUserLimit();
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class UserService {
private Long userLimit;
public Long getUserLimit() {
return userLimit;
}
}
public class UserServiceTest {
private UserService userService;
public void testGetUserLimit() {
Long expected = 1000L;
Whitebox.setInternalState(userService, "userLimit", expected);
Long actual = userService.getUserLimit();
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class UserService {
private Long superUserId;
public boolean isNotSuperUser(Long userId) {
return !isSuperUser(userId);
}
private boolean isSuperUser(Long userId) {
return Objects.equals(userId, superUserId);
}
}
public class UserServiceTest {
public void testIsNotSuperUser() throws Exception {
Long userId = 1L;
boolean expected = false;
UserService userService = PowerMockito.spy(new UserService());
PowerMockito.when(userService, "isSuperUser", userId).thenReturn(!expected);
boolean actual = userService.isNotSuperUser(userId);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
public class UserServiceTest {
public void testIsNotSuperUser() throws Exception {
Long userId = 1L;
boolean expected = false;
UserService userService = PowerMockito.spy(new UserService());
PowerMockito.stub(PowerMockito.method(UserService.class, "isSuperUser", Long.class)).toReturn(!expected);
boolean actual = userService.isNotSuperUser(userId);
Assert.assertEquals("返回值不相等", expected, actual;
}
}
public class UserServiceTest9 {
public void testIsSuperUser() throws Exception {
Long userId = 1L;
boolean expected = false;
UserService userService = new UserService();
Method method = PowerMockito.method(UserService.class, "isSuperUser", Long.class);
Object actual = method.invoke(userService, userId);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
(PowerMockRunner.class)
({UserService.class})
public class UserServiceTest10 {
public void testIsNotSuperUser() throws Exception {
Long userId = 1L;
boolean expected = false;
UserService userService = PowerMockito.spy(new UserService());
PowerMockito.when(userService, "isSuperUser", userId).thenReturn(!expected);
boolean actual = userService.isNotSuperUser(userId);
PowerMockito.verifyPrivate(userService).invoke("isSuperUser", userId);
Assert.assertEquals("返回值不相等", expected, actual);
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ TargetClass.class })
public class UserService {
private UserDAO userDAO;
public void modifyUser(UserVO userVO) {
UserDO userDO = new UserDO();
BeanUtils.copyProperties(userVO, userDO);
userDAO.modify(userDO);
}
}
(PowerMockRunner.class)
public class UserServiceTest {
private UserDAO userDAO;
private UserService userService;
public void testCreateUser() {
UserVO userVO = new UserVO();
userVO.setId(1L);
userVO.setName("changyi");
userVO.setDesc("test user");
userService.modifyUser(userVO);
ArgumentCaptor<UserDO> argumentCaptor = ArgumentCaptor.forClass(UserDO.class);
Mockito.verify(userDAO).modify(argumentCaptor.capture());
UserDO userDO = argumentCaptor.getValue();
Assert.assertNotNull("用户实例为空", userDO);
Assert.assertEquals("用户标识不相等", userVO.getId(), userDO.getId());
Assert.assertEquals("用户名称不相等", userVO.getName(), userDO.getName());
Assert.assertEquals("用户描述不相等", userVO.getDesc(), userDO.getDesc());
}
}
public class UserService {
private UserDAO userDAO;
public void modifyUser(UserVO userVO) {
UserDO userDO = new UserDO();
BeanUtils.copyProperties(userVO, userDO);
userDAO.modify(userDO);
}
}
(PowerMockRunner.class)
public class UserServiceTest {
private UserDAO userDAO;
private UserService userService;
private ArgumentCaptor<UserDO> argumentCaptor;
public void beforeTest() {
MockitoAnnotations.openMocks(this);
}
public void testCreateUser() {
UserVO userVO = new UserVO();
userVO.setId(1L);
userVO.setName("changyi");
userVO.setDesc("test user");
userService.modifyUser(userVO);
Mockito.verify(userDAO).modify(argumentCaptor.capture());
UserDO userDO = argumentCaptor.getValue();
Assert.assertNotNull("用户实例为空", userDO);
Assert.assertEquals("用户标识不相等", userVO.getId(), userDO.getId());
Assert.assertEquals("用户名称不相等", userVO.getName(), userDO.getName());
Assert.assertEquals("用户描述不相等", userVO.getDesc(), userDO.getDesc());
}
}
A:Automatic(自动化)
I:Independent(独立性)
R:Repeatable(可重复)
B:Border,边界值测试,包括循环边界、特殊取值、特殊时间点、数据顺序等。
C:Correct,正确的输入,并得到预期的结果。
D:Design,与设计文档相结合,来编写单元测试。
E:Error,强制错误信息输入(如:非法数据、异常流程、业务允许外等),并得到预期的结果。
面向对象是Java语言之中最为重要的特征。本课程共32章,详细讲解面向对象的定义、类与对象的组成、内存分析、封装性、继承性、多态性等基础概念,以及面向对象之中重要的代码模型、数据分析方式、核心设计模式原理与分析使用。
点击“阅读原文”开始学习吧~