使用Mockito测试Java HBase API



这是我正在测试的方法。此方法基于特定ID从HBase数据库中获取一些字节,在这种情况下,称为DTMID。我之所以要返回一些特定值的原因是因为我意识到没有办法知道ID是否总是在HBase中。另外,列族和列名称可能会更改。

@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);

如何更换

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

与...

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

相关内容

  • 没有找到相关文章