使用Mockito测试Java Hbase API

时间:2015-05-07 16:22:55

标签: unit-testing junit hbase mockito

这是我正在测试的方法。此方法基于特定的id从Hbase数据库获取一些字节,在本例中称为dtmid。我之所以想要返回一些特定值的原因是因为我意识到无法知道id是否总是在Hbase中。此外,列Family和列名称可能会更改。

@Override
   public void execute(Tuple tuple, BasicOutputCollector collector) {
      try {
        if (tuple.size() > 0) {
            Long dtmid = tuple.getLong(0);

            byte[] rowKey = HBaseRowKeyDistributor.getDistributedKey(dtmid);
            Get get = new Get(rowKey);
            get.addFamily("a".getBytes());
            Result result = table.get(get);
            byte[] bidUser = result.getValue("a".getBytes(),
                    "co_created_5076".getBytes());
            collector.emit(new Values(dtmid, bidUser));
        }

    } catch (IOException e) {
        e.printStackTrace();

    }

}

在我的主类上调用此方法时,我想返回一个特定的值。该方法应返回一些字节。

    byte[] bidUser = result.getValue("a".getBytes(),
                    "co_created_5076".getBytes());

这就是我在单元测试中所拥有的。

   @Test
   public void testExecute() throws IOException {
      long dtmId = 350000000770902930L;
      final byte[] COL_FAMILY = "a".getBytes();
      final byte[] COL_QUALIFIER = "co_created_5076".getBytes();

      //setting a key value pair to put in result
      List<KeyValue> kvs = new ArrayList<KeyValue>();
      kvs.add(new KeyValue("--350000000770902930".getBytes(), COL_FAMILY, COL_QUALIFIER, Bytes.toBytes("ExpedtedBytes")));
      // I create an Instance of result
      Result result = new Result(kvs);

      // A mock tuple with a single dtmid
      Tuple tuple = mock(Tuple.class);
      bolt.table = mock(HTable.class);
      Result mcResult = mock(Result.class);
      when(tuple.size()).thenReturn(1);
      when(tuple.getLong(0)).thenReturn(dtmId);
      when(bolt.table.get(any(Get.class))).thenReturn(result);
      when(mcResult.getValue(any(byte[].class), any(byte[].class))).thenReturn(Bytes.toBytes("Bytes"));

      BasicOutputCollector collector = mock(BasicOutputCollector.class);

      // Execute the bolt.
      bolt.execute(tuple, collector);


      ArgumentCaptor<Values> valuesArg = ArgumentCaptor
            .forClass(Values.class);
      verify(collector).emit(valuesArg.capture());

      Values d = valuesArg.getValue();
      //casting this object in to a byteArray.
      byte[] i = (byte[]) d.get(1);

      assertEquals(dtmId, d.get(0));
   }

我在这里使用它来返回我的字节。由于某种原因不起作用。

  when(mcResult.getValue(any(byte[].class), any(byte[].class))).thenReturn(Bytes
        .toBytes("myBytes"));

由于某种原因,当我捕获值时,我仍然得到我在此处指定的字节:

  List<KeyValue> kvs = new ArrayList<KeyValue>();
    kvs.add(new KeyValue("--350000000770902930".getBytes(),COL_FAMILY,       COL_QUALIFIER, Bytes
            .toBytes("ExpedtedBytes")));
    Result result = new Result(kvs);

1 个答案:

答案 0 :(得分:1)

如何更换

when(bolt.table.get(any(Get.class))).thenReturn(result);

...与

when(bolt.table.get(any(Get.class))).thenReturn(mcResult);