Java Unit Test - Mockito mock静态方法

2021/6/25 20:27:19

本文主要是介绍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);

        }
    }
}

  



这篇关于Java Unit Test - Mockito mock静态方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程