编程语言
首页 > 编程语言> > Java Unit Test - Mockito mock静态方法

Java Unit Test - Mockito mock静态方法

作者:互联网

当需要mock静态方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是静态方法所在的类。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;

@RunWith(PowerMockRunner.class)
@PrepareForTest(String.class)
public class MockPrepareForTest {

    @Test
    public void testStaticMathod () {
        TestString testString = new TestString();

        PowerMockito.mockStatic(String.class);
        PowerMockito.when(String.valueOf(eq(100l))).thenReturn("TEST");

        String result = testString.getTestString(100l);

        assertEquals("TEST", result);
    }

    class TestString {

        public String getTestString(long number) {
            return String.valueOf(number);

        }
    }
}

  

标签:PowerMockito,静态方法,String,Mockito,PrepareForTest,org,import,class,Unit
来源: https://www.cnblogs.com/codedddddd/p/14931859.html