junit withcapture

JMockit 允许在 Verifications 代码块中通过 withCapture 方法捕获重放阶段传递的方法参数,分为 3 种情况:

  1. 捕获单次方法调用的参数
  2. 捕获多次方法调用的参数集合
  3. 捕获方法调用时新创建的对象

具体示例如下:

@Test
public void capturingSingle() {
    userService.checkPassword(1001L, "aaa");

    new Verifications() {
        {
            // 捕获单次方法调用的参数
            long uid;
            String pwd;
            userService.checkPassword(uid = this.withCapture(), pwd = this.withCapture());
            Assert.assertEquals(1001L, uid);
            Assert.assertEquals("aaa", pwd);
        }
    };
}

@Test
public void capturingMultiple() {
    userService.getUserInfo(1001L);
    userService.getUserInfo(1002L);
    userService.getUserInfo(1003L);

    new Verifications() {
        {
            // 捕获多次方法调用的参数集合
            List<Long> userIds = new ArrayList<>();
 userService.getUserInfo(this.withCapture(userIds));
            Assert.assertEquals(3, userIds.size());
            Assert.assertEquals(Arrays.asList(1001L, 1002L, 1003L), userIds);
        }
    };
}

@Test
public void capturingNewInstances(@Mocked User user) { // 不要忘了 @Mocked User
    userService.updateUserInfo(new User(1001L, "zhangsan", 16));
    userService.updateUserInfo(new User(1002L, "lisi", 17));
    userService.updateUserInfo(new User(1003L, "wanger", 18));

    new Verifications() {
        {
            // 捕获方法调用时新创建的对象
            List<User> users = this.withCapture(new User(anyLong, anyString, anyInt));
            Assert.assertEquals(3, users.size());
            List<User> userInfos = new ArrayList<>();
            userService.updateUserInfo(this.withCapture(userInfos));
            Assert.assertEquals(users, userInfos);
        }
    };
}
 
posted @ 2019-10-23 14:49  拓睿峰  阅读(1329)  评论(0编辑  收藏  举报