簡體   English   中英

如何模擬類的實例變量?

[英]How to mock instance variable of class?

我如何模擬在類級別實例化的變量..我想模擬 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 方法,它也沒有將我的“值”作為我的返回值返回。

先進的感謝......:D

看看https://code.google.com/p/mockito/wiki/MockingObjectCreation - 那里有一些想法可以幫助你。

正如 fge 的評論:

所有用法都需要在類級別注釋@RunWith(PowerMockRunner.class)@PrepareForTest

確保您正在使用該測試運行程序,並且將@PrepareForTest(GenUser.class)放在您的測試類上。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM