如何使用Mockito / Powermockito测试方法

时间:2016-10-07 10:20:53

标签: java unit-testing junit mockito powermockito

我有一个需要进行单元测试的课程:

public class AMQProducer {

     private final String TCP = "tcp://";
     private final String COLON = ":";

     AMQProducer() {

     }

     public AMQProducer(String ip, long port) throws JMSException {
      try {
       ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(TCP + ip + COLON + port);
       Connection connection = connectionFactory.createConnection();
      } catch (JMSException e) {
       throw e;
      }
     }
    }

我有一个测试用例:

@RunWith(PowerMockRunner.class)
@PrepareForTest()
public class TestAMQProducer {

 @Mock
 Connection connection;

 @Mock
 ActiveMQConnectionFactory connectionFactory;

 @Test
 public void test() throws Exception {
  PowerMockito.whenNew(ActiveMQConnectionFactory.class).withAnyArguments().thenReturn(connectionFactory);
  PowerMockito.when(connectionFactory.createConnection()).thenReturn(connection);
  AMQProducer producer = new AMQProducer("random", 1234);
 }
}

当我运行测试用例时,未使用ActiveMQConnectionFactory的模拟对象。相反,正在使用实际的实现,并且正在建立TCP连接:

javax.jms.JMSException: Could not connect to broker URL: tcp://random:2333. Reason: java.net.UnknownHostException: random

我尝试过Powermockito和Mockito,但两者都失败了。如何模拟对象以及如何成功运行测试用例?

我是单位测试的新手并试图从各个社区获得帮助,但没有找到合适的答案。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您无法使用代码的当前结构对其进行测试 - 您在构造函数中创建new ActiveMQConnectionFactory。改为使用依赖注入。

Mockito:

public class AMQProducer {

    AMQProducer() {}

    public AMQProducer(ActiveMQConnectionFactory connectionFactory) throws JMSException {
        Connection connection = connectionFactory.createConnection();
    }

}

public class TestAMQProducer {

    private final Connection connection = mock(Connection.class);
    private final ActiveMQConnectionFactory connectionFactory = mock(ActiveMQConnectionFactory.class);

    @Test
    public void test() throws Exception {
        doReturn(connection).when(connectionFactory).createConnection();

        // actual test here
    }

}