如何模拟类的实例变量?

时间:2013-06-19 07:49:39

标签: java junit4 mockito powermock

我如何模拟在类级别实例化的变量..我想模拟GenUser,UserData。我该怎么做......

我有以下课程

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();
    }
}

我如何模仿我的v1就像这样

GenUser gu=Mockito.mock(GenUser.class);
PowerMockito.whenNew(GenUser.class).withNoArguments().thenReturn(gu);

我为单元测试和模拟编写的是

@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);
}

即使我已经模仿了GenUser v1的persistUser方法,那么它也没有返回“Value”作为我的返回值。

感谢adavanced .......:D

3 个答案:

答案 0 :(得分:2)

看看https://code.google.com/p/mockito/wiki/MockingObjectCreation - 有一些想法可以帮到你。

答案 1 :(得分:2)

与fge的评论一样:

  

所有用法都需要在班级注释@RunWith(PowerMockRunner.class)@PrepareForTest

确保您正在使用该测试运行器,并且已将@PrepareForTest(GenUser.class)放在测试类上。

(资料来源:https://code.google.com/p/powermock/wiki/MockitoUsage13

答案 2 :(得分:0)

我不知道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);
    }
}