13-14. @InjectMocks、@Captor、ArgumentCaptor、captor.capture()、captor.getValue()
@InjectMocks修饰的对象,会创建一个真实对象,会调用真实方法(若方法中再调用对象中的其他方法时,也是调用真实方法)
package lesson13_14; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ArgumentCaptorTest { @Mock private List<String> list; @Mock private UserDao userDao; @Captor private ArgumentCaptor<User> captorAnnotation; /** * @InjectMocks作用: * 1.构造注入: * 通过UserService的构造函数将Mock的userDao注入UserService,等价于UserService userService = new UserService(userDao); * 2.会调用修饰对象的真实方法 * */ @InjectMocks UserService userService; @Test public void test() { ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); when(list.add("test")).thenReturn(true); list.add("test"); verify(list).add(captor.capture()); assertThat(captor.getValue(), equalTo("test")); } @Test public void test2() { User user = new User(1); when(userDao.delUser(user)).thenReturn(true); assertThat(userService.delUser(user), equalTo(true)); assertThat(user.getType(), equalTo("D")); } @Test public void test3() { ArgumentCaptor<User> captor = ArgumentCaptor.forClass(User.class); User user = new User(1); when(userDao.delUser(user)).thenReturn(true); boolean result = userService.delUser(user); assertThat(result, equalTo(true)); verify(userDao).delUser(captor.capture()); assertThat(captor.getValue().getType(), equalTo("D")); } @Test public void testAnnotation() { User user = new User(1); when(userDao.delUser(user)).thenReturn(true); boolean result = userService.delUser(user); assertThat(result, equalTo(true)); verify(userDao).delUser(captorAnnotation.capture()); assertThat(captorAnnotation.getValue().getType(), equalTo("D")); } }
package lesson13_14; public class UserService { private final UserDao userDao; public UserService(UserDao userDao) { this.userDao = userDao; } public boolean delUser(User user){ user.setType("D"); return userDao.delUser(user); } }
package lesson13_14; public class UserDao { public boolean delUser(User user) { throw new RuntimeException(); } }
package lesson13_14; public class User { private final Integer id; private String type; public User(Integer id) { this.id = id; } public Integer getId() { return id; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "User{" + "id=" + id + ", type='" + type + '\'' + '}'; } }