Mockito单元测试最佳实践

发布时间 2023-07-27 19:57:30作者: 徐浩进
Mockito可以帮助我们模拟创建对象,经常用于模拟外系统、数据库、及其它方法中调用的对象
 
使用mockito时,单元测试类需要加上注解 @RunWith(MockitoJUnitRunner.class),在@Before方法中加上 MockitoAnnotations.openMocks(this);
使用spring框架时,经常使用@Autowired注解,在这里被注入的对象使用@InjectMocks,而要注入的对象使用@Mock
 
使用示例:
public class UresCrewAddDispatcherTest {

    @InjectMocks
    UresCrewAddDispatcher dispatcher;

    @Mock
    UresCrewAddService uresCrewAddService;

    @Before
    public void init() throws Exception {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void process() {
        Mockito.when(uresCrewAddService.addUresCrewDetail(Mockito.any())).thenReturn(true);

        boolean result = dispatcher.process(new UresCrewDetail());

        Assert.assertTrue(result);
    }

}
 
其中UresCrewAddDispatcher是被注入的对象,UresCrewAddService要进行注入的对象