2013-06-19 74 views
2

我如何模擬在類級別實例化的變量..我想模擬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的persistUser方法v1的那麼它也沒有回我「價值」爲我的迴歸v人。

感謝adavanced .......:d

+0

如何創建'obj'? – fge

+0

我已經改變obj請檢查.... – swan

+2

好吧,我不知道PowerMockito(我不必使用它;)),但它不需要'@ PrepareForMock'或什麼?您的代碼提取不會顯示 – fge

回答

2

如FGE的評論:

所有用法要求@RunWith(PowerMockRunner.class)@PrepareForTest在類級別註解。

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

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

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