2014-10-11 67 views
5

考慮這個如何模擬在方法內創建的對象?

public class UserManager { 
    private final CrudService crudService; 

    @Inject 
    public UserManager(@Nonnull final CrudService crudService) { 
     this.crudService = crudService; 
    } 

    @Nonnull 
    public List<UserPresentation> getUsersByState(@Nonnull final String state) { 
     return UserPresentation.getUserPresentations(new UserQueries(crudService).getUserByState(state)); 
    } 

} 

我想模擬出

new UserQueries(crudService) 

,這樣我可以模擬出其行爲

任何想法?

+0

這也許可以幫助:http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Spy.html – 2014-10-11 23:11:06

回答

2

您可以注入一個創建UserQueries的工廠。

public class UserManager { 
private final CrudService crudService; 
private final UserQueriesFactory queriesFactory; 

@Inject 
public UserManager(@Nonnull final CrudService crudService,UserQueriesFactory queriesFactory) { 
    this.crudService = crudService; 
    this.queriesFactory = queriesFactory; 
} 

@Nonnull 
public List<UserPresentation> getUsersByState(@Nonnull final String state) { 
    return UserPresentation.getUserPresentations(queriesFactory.create(crudService).getUserByState(state)); 
} 

}

雖然它可能是更好的(如果你要做到這一點)以注入CrudService進廠。

8

PowerMock你可以模擬構造函數。見example

我不是一個IDE的權利,但會是這樣的:

UserQueries userQueries = PowerMockito.mock(UserQueries.class); 
    PowerMockito.whenNew(UserQueries.class).withArguments(Mockito.any(CrudService.class)).thenReturn(userQueries); 

您需要使用PowerMockRunner運行測試(這些註釋添加到您的測試類):

@RunWith(PowerMockRunner.class) 
@PrepareForTest(UserQueries .class) 

如果你不能使用PowerMock,你必須注入一個工廠,因爲它說@Briggo答案。

希望它可以幫助