Java单元测试之mock方法

Mock一个简单方法

//given
ClassTest test = Mockito.mock(ClassTest.class);
Object result = new Object();

//when
Mockito.when(test.methodOne()).thenReturn(result);

//then
Assert.assertEquals(test.methodOne(), result);

让某个方法调用真实实现

//given
ClassTest test = Mockito.mock(ClassTest.class);

//when
Mockito.when(test.methodOne()).thenCallRealMethod();

//then
Assert.assertEquals(test.methodOne(), null);

其实Mockito.mock()外还有一个方法Mockito.spy(), 这样mock出来的类, 只要没有指定when去mock的方法, 都会默认调用真实实现

//given
ClassTest test = Mockito.spy(new ClassTest());
Object result = new Object();

//when
Mockito.doReturn(result).when(test).methodOne();//注意这里最好这样mock

//then
Assert.assertEquals(test.methodOne(), result);
Assert.assertEquals(test.methodTwo(), result);//会调用真实实现

Mock静态方法

这里要用到另一个库PowerMokito

@RunWith(PowerMockRunner.class)
@PrepareForTest(YourMockStaticClass.class)
public class Mocker {

    @Test
    public void testOne() throws Exception {

        //given
        PowerMockito.mockStatic(YourMockStaticClass.class);
        BDDMockito.given(YourMockStaticClass.staticMethod(...)).willReturn(...);

        //when
        sut.execute(); 

        //then
        PowerMockito.verifyStatic();
        YourMockStaticClass.staticMethod(...);

    }

Mock void方法

//given
ClassTest test = Mockito.mock(ClassTest.class);

//when
Mockito.doNothing().when(test).voidMethod();

//then
Mockito.verify(test, Mockito.times(1)).voidMethod();

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Scroll to Top