如何模拟类的实例变量



如何模拟在类级别实例化的变量…我想模拟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方法,那么它也没有返回我"值"作为我的返回值。

thanks in advanced .......:D

正如fge的评论:

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

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

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

看看https://code.google.com/p/mockito/wiki/MockingObjectCreation -那里有一些想法可能会对你有所帮助。

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

相关内容

  • 没有找到相关文章

最新更新