代码看起来像这样
public GetPortfoliosResponse retrievePortfolios(RequestIdentityInfo requestIdentityInfo, GetPortfoliosRequest getPortfoliosRequest) {
PortfolioReferenceParameter portfolioReferenceParameter = new PortfolioReferenceParameter();
//some code
List<Portfolio> portfolios = portfolioReferenceParameter.getPortfolios();
}
在我的测试课中,我正在做这样的事情
@Mock
private PortfolioReferenceParameter portfolioReferenceParameter;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
List<Portfolio> portfolios = new ArrayList<Portfolio>();
//code to build the list
when(portfolioReferenceParameter.getPortfolios()).thenReturn(portfolios);
}
但这似乎不起作用。
当我调用serviceimpl方法时,它仍然使用在该方法中本地创建的PortfolioReferenceParameter的实际对象。如何用我的对象模拟该对象?
答案 0 :(得分:0)
Mockito不支持模拟构造函数 - 您需要使用PowerMock whenNew
- 请参阅https://code.google.com/p/powermock/wiki/MockitoUsage13。
更好的方法是重构您的retrievePortfolios方法,将PortfolioReferenceParameter的实例作为参数并在测试中注入模拟
public class AppTest {
@Mock
private PortfolioReferenceParameter referenceParam;
private List portfolios = new ArrayList();
@Before
public void setUp() {
when(referenceParam.getPortfolios())
.thenReturn(portfolios);
}
@Test
public void testApp() {
GetPortfoliosResponse response = retrievePortfolios(requestIdentityInfo, getPortfoliosRequest, referenceParam);
// assert response details
}
}