我一整天都坚持这个问题。尝试了许多资源和调试功能,但没有运气。
你能帮我吗?
public class Data{
DataDriver dataDriver; // DataDriver is a different class which I have injected.
Connector connector; // Connector is a different class which I am injecting in Data class.
// Constructor and Setter methods
public void read(){
CloseableHttpClient client = HttpClients.createDefault();
Hashmap<String, String> credentials = dataDriver.run(new Date());
HttpGet get = connector.execute(client,credentials);
}
}
对于我的测试类,我使用的是Powermockito,因为HttClients.createDefault()
是一个静态方法。
@ContextConfiguration(locations = { "classpath:/XXX.xml" })
@RunWith(PowerMockRunner.class)
public class DataTest {
Data mockeddata;
@Mock
Connector mockedconnector;
@Mock
DataDriver mockeddataDriver;
@Mock
CloseableHttpClient mockedClient;
@Before
public void Setup() {
MockitoAnnotations.initMocks(Data.class);
mockeddata =new Data();
PowerMockito.mockStatic(HttpClients.class);
mockedData.setConnector(mockedconnector);
mockedData.setDataDriver(mockedDataDriver);
}
@Test
@PrepareForTest({ HttpClients.class })
public void testRead(){
HashMap<String, String> credentials = new HashMap<String, String>();
PowerMockito.when(HttpClients.createDefault()).thenReturn(mockedClient);
PowerMockito.when(mockeddataDriver.run(newDate())).thenReturn(credentials);
PowerMockito.when(mockedconnector.execute(mockedClient,credentials)).thenReturn(new HttpGet());
verify(mockedconnector, atLeastOnce()).execute(mockedClient, credentials);
}
}
它表示与连接器模拟的零交互。它没有抱怨dataDriver模拟。我尝试调试,并能够在Data类中看到我的两个模拟对象。但它不会进入连接器的执行功能。
关于我做错了什么建议?
谢谢
答案 0 :(得分:0)
也许当您验证参数Mockito正在创建不同的对象引用(不同的对象)时......
尝试使用eq()
方法进行验证,以确保您期望的参数与之前定义的when
相同。
verify(mockedconnector,atLeastOnce()).execute(eq(mockedClient),eq(credentials));
答案 1 :(得分:0)
您没有从测试类中调用read
方法。