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