首页  

mockito 实例     所属分类 unit-test 浏览量 531
mockito
Tasty mocking framework for unit tests in Java

https://site.mockito.org/

https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
https://javadoc.io/doc/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html


待测的类标注为 @InjectMocks,将其依赖的其他类标注为 @Mock 使用 MockitoAnnotations.initMocks 或 @RunWith(MockitoJUnitRunner.class) 进行mock 注入 @RunWith(MockitoJUnitRunner.class) 的作用 this runner adds following behavior: Initializes mocks annotated with @Mock so that explicit usage of MockitoAnnotations#initMocks(Object) is not necessary. Mocks are initialized before each test method.
public class OrderServiceTest { @InjectMocks OrderServiceImpl orderService; @Mock private OrderDao orderDao; @Before public void setUp(){ MockitoAnnotations.initMocks(this); }
@RunWith(MockitoJUnitRunner.class) public class OrderServiceTest2 { @InjectMocks OrderServiceImpl orderService; @Mock private OrderDao orderDao;
Order order = new Order(); Mockito.when(orderDao.getOrderById(Mockito.anyInt())).thenReturn(order);
OrderServiceTest package dyyx.demo.order; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class OrderServiceTest { @InjectMocks OrderServiceImpl orderService; @Mock private OrderDao orderDao; @Before public void setUp(){ // 不使用 @RunWith(MockitoJUnitRunner.class) ,需要显式初始化 MockitoAnnotations.initMocks(this); } @Test public void getOrderByIdTest() { System.out.println("OrderServiceTest.getOrderByIdTest run"); Order order = new Order(); order.setId(9); Mockito.when(orderDao.getOrderById(Mockito.anyInt())).thenReturn(order); System.out.println(orderService.getOrderById(1)); System.out.println(orderService.getOrderById(2)); } @Test public void getOrderByIdTest2() { System.out.println("OrderServiceTest.getOrderByIdTest2 run"); Order order = new Order(); order.setId(888); Mockito.when(orderDao.getOrderById(Mockito.anyInt())).thenReturn(order); // orderDao = Mockito.mock(OrderDao.class); System.out.println(orderService.getOrderById(1)); System.out.println(orderService.getOrderById(2)); } }
完整代码 https://gitee.com/dyyx/hellocode/tree/master/demo/springboot1.5.4demo/src/test/java/dyyx/demo/order

上一篇     下一篇
Spring ProxyFactory 和 方法拦截器 MethodInterceptor

Spring AOP @Aspect

powermock 静态方法mock

Mocktio 指南

Mockito mock 和 spy 区别

mock 与 字节码生成工具