2017-10-19 159 views
0

我有下面的方法,我需要單元測試。如何使用靜態內部類來模擬對象的實例化?

如何在下面模擬創建LDUser對象?

public void isFeatureFlagOn(String featureFlagId, TransactionContext transContext, boolean defaultReturnState) 
    throws TAServiceException { 
     boolean returnState = defaultReturnState; 
     try { 
      LDUser ldUser = new LDUser.Builder(transContext.getAuthId()).build(); 
      returnState = ldClient.boolVariation(featureFlagId, ldUser, defaultReturnState); 
     } catch (Exception e) { 
      returnState = defaultReturnState; 
     } 

     if (!returnState) { 
      throw new TAServiceException("This service is not available", HttpStatus.NOT_FOUND); 
     } 
    } 
+0

是[我的文章](https://github.com/mockito/mockito/wiki/Mocking-Object-Creation)有什麼用? –

回答

0

這真的不可行,除非你使用PowerMock這樣的東西。但是,您可能需要考慮注入LDUser構建器,以便在調用測試方法時可以嘲笑構建器。通過構建器模擬,你可以模擬它如何構建你想要的模擬LDUser實例。所以,你的測試方法看起來是這樣的:

// ... 
when(mockLdUserBuilder.build()).thenReturn(mockLdUser); 
classUnderTest.methodUnderTest(mockLdUserBuilder); 
// ... assert/verify stuff 
0

您可以創建可用於注入嘲笑建設者一個package水平的方法。

public void isFeatureFlagOn(...) throws TAServiceException { 
    boolean returnState = defaultReturnState; 
    try { 
     getBuilder(transContext.getAuthId()).build(); 
     ... 
    } 
    ... 
} 
//package method 
Builder getBuilder(int authId) { 
    return new LDUser.Builder(authId); 
} 

然後在您的測試中,您可以重寫此方法。

@Mock 
LDUser.Builder builder; 

@Test 
public void test1() { 
    MyClass myClass = new MyClass() { 
    @Override 
    Builder getBuilder(int authId) { 
     return builder; 
    } 
    } 
    myClass.isFeatureFlagOn(...); 
    ... 
} 
相關問題