java 如何模拟类的实例变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17185700/
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 instance variable of class?
提问by swan
How do i mock the variables instantiated at class level..I want to mock GenUser,UserData. how do i do it...
我如何模拟在类级别实例化的变量..我想模拟 GenUser、UserData。我该怎么做...
I have following class
我有以下课程
public class Source {
private GenUser v1 = new GenUser();
private UserData v2 = new UserData();
private DataAccess v3 = new DataAccess();
public String createUser(User u) {
return v1.persistUser(u).toString();
}
}
how do i mocked my v1 is like this
我如何嘲笑我的 v1 是这样的
GenUser gu=Mockito.mock(GenUser.class);
PowerMockito.whenNew(GenUser.class).withNoArguments().thenReturn(gu);
what i have written for unit test and to mock is that
我为单元测试和模拟编写的内容是
@Test
public void testCreateUser() {
Source scr = new Source();
//here i have mocked persistUser method
PowerMockito.when(v1.persistUser(Matchers.any(User.class))).thenReturn("value");
final String s = scr.createUser(new User());
Assert.assertEquals("value", s);
}
even if i have mocked persistUser method of GenUser v1 then also it did not return me "Value" as my return val.
即使我嘲笑了 GenUser v1 的 persistUser 方法,它也没有将“值”作为我的返回值返回。
thanks in adavanced.......:D
先进的感谢......:D
采纳答案by Jeff Bowman
As in fge's comment:
正如 fge 的评论:
All usages require
@RunWith(PowerMockRunner.class)
and@PrepareForTest
annotated at class level.
所有的用法要求
@RunWith(PowerMockRunner.class)
,并@PrepareForTest
在类级别注解。
Make sure you're using that test runner, and that you put @PrepareForTest(GenUser.class)
on your test class.
确保您正在使用该测试运行程序,并且您已将其放入@PrepareForTest(GenUser.class)
您的测试类中。
(Source: https://code.google.com/p/powermock/wiki/MockitoUsage13)
(来源:https: //code.google.com/p/powermock/wiki/MockitoUsage13)
回答by Dawood ibn Kareem
Have a look at https://code.google.com/p/mockito/wiki/MockingObjectCreation- there are a couple of ideas there that may help you.
看看https://code.google.com/p/mockito/wiki/MockingObjectCreation- 有一些想法可以帮助你。
回答by HardcoreBro
I don't know mockito, but if you don't mind using PowerMock and EasyMock, the following would work.
我不知道 mockito,但如果你不介意使用 PowerMock 和 EasyMock,下面的方法是可行的。
@Test
public void testCreateUser() {
try {
User u = new User();
String value = "value";
// setup the mock v1 for use
GenUser v1 = createMock(GenUser.class);
expect(v1.persistUser(u)).andReturn(value);
replay(v1);
Source src = new Source();
// Whitebox is a really handy part of PowerMock that allows you to
// to set private fields of a class.
Whitebox.setInternalState(src, "v1", v1);
assertEquals(value, src.createUser(u));
} catch (Exception e) {
// if for some reason, you get an exception, you want the test to fail
e.printStackTrack();
assertTrue(false);
}
}