Java 如何从 JMockit 模拟静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26408253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock a static method from JMockit
提问by Roshanck
I have a static method which will be invoking from test method in a class as bellow
我有一个静态方法,它将从类中的测试方法调用,如下所示
public class MyClass
{
private static boolean mockMethod( String input )
{
boolean value;
//do something to value
return value;
}
public static boolean methodToTest()
{
boolean getVal = mockMethod( "input" );
//do something to getVal
return getVal;
}
}
I want to write a test case for method methodToTestby mocking mockMethod. Tried as bellow and it doesn't give any output
我想通过模拟 mockMethod为方法methodToTest编写一个测试用例。如下尝试,它没有给出任何输出
@Before
public void init()
{
Mockit.setUpMock( MyClass.class, MyClassMocked.class );
}
public static class MyClassMocked extends MockUp<MyClass>
{
@Mock
private static boolean mockMethod( String input )
{
return true;
}
}
@Test
public void testMethodToTest()
{
assertTrue( ( MyClass.methodToTest() );
}
回答by jchen86
To mock your static method:
模拟你的静态方法:
new MockUp<MyClass>()
{
@Mock
boolean mockMethod( String input ) // no access modifier required
{
return true;
}
};
回答by Guest Poster
To mock the static private method:
模拟静态私有方法:
@Mocked({"mockMethod"})
MyClass myClass;
String result;
@Before
public void init()
{
new Expectations(myClass)
{
{
invoke(MyClass.class, "mockMethod", anyString);
returns(result);
}
}
}
@Test
public void testMethodToTest()
{
result = "true"; // Replace result with what you want to test...
assertTrue( ( MyClass.methodToTest() );
}
From JavaDoc:
来自 JavaDoc:
Object mockit.Invocations.invoke(Class methodOwner, String methodName, Object... methodArgs)
Specifies an expected invocation to a given static method, with a given list of arguments.
Object mockit.Invocations.invoke(Class methodOwner, String methodName, Object... methodArgs)
使用给定的参数列表指定对给定静态方法的预期调用。