单元测试 - Mockito - 2
3. Mockito 中常用注解
3.1 可以代替 Mock 方法的 @Mock 注解
Shorthand for mocks creation - @Mock annotation
Important! This needs to be somewhere in the base class or a test runner:
快速 mock 的方法,使用 @mock
注解。
mock 注解需要搭配 MockitoAnnotations.openMocks(testClass) 方法一起使用。
@Mock
private Random random;
@Test
void check() {
MockitoAnnotations.openMocks(this);
Mockito.when(random.nextInt()).thenReturn(100);
Assertions.assertEquals(100, random.nextInt());
}
3.2 @BeforeEach 与 @BeforeAfter 注解
@Mock
private Random random;
@BeforeEach
void setUp() {
System.out.println("----测试开始----");
}
@Test
void check() {
MockitoAnnotations.openMocks(this);
Mockito.when(random.nextInt()).thenReturn(100);
Assertions.assertEquals(100, random.nextInt());
}
@AfterEach
void after() {
System.out.println("----测试结束----");
}
而在 Junit5 中,@Before 和 @After 注解被 @BeforeEach
和 @AfterEach
所替代。
3.3 Spy 方法与 @Spy 注解
spy() 方法与 mock() 方法不同的是
- 被 spy 的对象会走真实的方法,而 mock 对象不会
- spy() 方法的参数是对象实例,mock 的参数是 class
示例:spy 方法与 Mock 方法的对比
@Test
void check() {
CheckAuthorityImpl checkAuthority = Mockito.spy(new CheckAuthorityImpl());
int res = checkAuthority.add(1, 2);
Assertions.assertEquals(3, res);
CheckAuthorityImpl checkAuthority1 = Mockito.mock(CheckAuthorityImpl.class);
int res1 = checkAuthority1.add(1, 2);
Assertions.assertEquals(3, res1);
}
输出结果
// 第二个 Assertions 断言失败,因为没有给 checkAuthority1 对象打桩,因此返回默认值
org.opentest4j.AssertionFailedError:
Expected :3
Actual :0
使用 @Spy
注解代码示例
@Spy
private CheckAuthorityImpl checkAuthority;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void check() {
int res = checkAuthority.add(1, 2);
Assertions.assertEquals(3, res);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构