创建对象不使用注射剂会导致HTTPCLIENT的问题



我有一个具有默认构造函数的类。在此构造函数中,许多成员的初始化如下:

public classs MyClass{
private String variable1=null;
private String param1="2000";
private String param2="2000";
public MyClass() {
        variable1 = getProperty("iaRequestPath");
        timeout = Integer.parseInt(getProperty("param1"));
        reuqestUrl = getProperty("reuqestUrl");
        try {
            String maxConnection = getProperty("maxConnection");
            int connections =0;
             int param3=0;
            param3 = validateMethod(maxConnection);//Here parse Int will happen
             param4 = validateResource(defaultMaxConnPerRoute);
            param5 = validateResource(maxConnPerIAroute);
            HttpCoreConnectionFactory factory = new HttpCoreConnectionFactory(parma1, param2, null, 0, 
                                                                null, "SOME_VALUE");
            httpclient = factory.getPooledHttpCoreClient(param3, param4, param5, reuqestUrl);
        } catch (Exception exp) {
        }
    }

如果我使用@InjectMocks,我将无法模拟构造函数成员,因为在我的测试类中进行模拟之前,将调用构造函数。我避免在测试类中使用注入模拟并手动创建对象。像MyClass testClass=new MyClass(); 并嘲笑

的httpclient
HttpClient httpClient =PowerMockito.mock(HttpClient.class);

httpclient总是在我的实际代码中抛出null 克服这种情况基本上我不需要httpclient的价值 从构造函数初始化中,我需要从模拟

尽管我嘲笑它没有被嘲笑的价值。

预先感谢。

我将使用PowerMock模拟工厂的创建。然后模拟getPooledHttpCoreClient方法以返回httpClient的模拟:

@RunWith(PowerMockRunner.class)
@PrepareForTest(HttpCoreConnectionFactory.class)
public class MyClassTest{

@Mock
private HttpCoreConnectionFactory factoryMock;
@Mock
private HttpClient httpClientMock;
@Before
public void init(){
   MockitoAnnotations.initMocks(this);
@Test
public void testMethod(){
    // Arrange
    PowerMockito.whenNew(HttpCoreConnectionFactory.class)
     .withArguments(Mockito.anyString(), Mockito.anyString()...).thenReturn(factoryMock);
    doReturn(httpClientMock).when(factoryMock)
        .getPooledHttpCoreClient(Mockito.anyString(), Mockito.anyString()...);
    // prepare the httpClientMock using when() etc..
    // Act
    MyClass myClass = new MyClass();
    // assertions

相关内容

  • 没有找到相关文章

最新更新