mockito单元测试示例_Mockito模拟示例

本文详细介绍了Mockito框架如何模拟类和方法,包括Mockito的mock()方法、@Mock注解、@InjectMocks批注、spy()方法以及@Spy注解的使用,展示了在单元测试中如何有效地模拟对象和行为。
摘要由CSDN通过智能技术生成

mockito单元测试示例

Mockito mocking framework provides different ways to mock a class. Let’s look at different methods through which we can mock a class and stub its behaviors.

Mockito模拟框架提供了模拟类的不同方法。 让我们看一下可以模拟类并存根其行为的不同方法。

Mockito模拟方法 (Mockito mock method)

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object.

我们可以使用Mockito类的mock()方法创建给定类或接口的模拟对象。 这是模拟对象的最简单方法。

package com.journaldev.mockito.mock;

import java.util.List;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class MockitoMockMethodExample {

	@SuppressWarnings("unchecked")
	@Test
	public void test() {
		// using Mockito.mock() method
		List<String> mockList = mock(List.class);
		when(mockList.size()).thenReturn(5);
		assertTrue(mockList.size()==5);
	}
	
}

We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.

我们使用JUnit 5与Mockito一起编写测试用例来模拟对象。

Mockito @模拟注解 (Mockito @Mock Annotation)

We can mock an object using @Mock annotation too. It’s useful when we want to use the mocked object at multiple places because we avoid calling

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值