1. 程式人生 > >專題:如何寫測試——HBase

專題:如何寫測試——HBase

最近做Spark Streaming任務時用到了HBase做中間狀態查詢和儲存,順手寫了一些測試,小小總結了一下各部分測試的寫法。話說這裡為什麼不用redis呢?Redis作為kv儲存系統還是太簡單了,HBase可以讓你少操很多很多心,這裡就不跑題了。

1. HBase和各類測試方法

  1. 利用HBaseTestObj的HBase的Put測試。個人認為沒什麼用,要檢查Put還不如直接檢查進入Put之前的內容。
  2. 使用MRUnit來測試MapReduce的HBase表輸入輸出,這一部分可以參照前一篇的MapReduce測試,本質與1是一致的,就是檢查Put物件(取出Put物件中的內容做比較,不要費神去自己構造Put物件了,神煩)。
  3. 使用HBase Mini Cluster的HBaseTestingUtility進行整合測試,網上的介紹是說啟動一次需要20-30秒,實測結果是比一般的測試慢不了多少,建議就直接使用這個,簡單並且統一,不用專門為了測試而測試。下面的例子都是以HBase Mini Cluster為基礎進行的測試。
  4. FakeHBase,沒有嘗試使用,看起來挺好的。

      一般來說只會使用其中的一種,選一個就好。

2. 測試用例

2.1 測試基本環境

  • 引入以下依賴,根據自己的情況進行調整,需要解決掉與原有依賴的衝突(下面的HBase的版本是公司內部版,酌情替換掉吧)
<dependency
>
<groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>2.4.0</version> <type>test-jar</type> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.hbase</groupId
>
<artifactId>hbase</artifactId> <version>0.94.11</version> <type>test-jar</type> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-hdfs</artifactId> <version>2.4.0</version> <type>test-jar</type> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-hdfs</artifactId> <version>2.4.0</version> <scope>test</scope> </dependency>
  • 測試的before/after單元中HTable的建立與關閉(雖然是Scala程式碼,但是應該不影響理解)。
class HBaseTest extends FlatSpec with BeforeAndAfterAll {
  private var utility: HBaseTestingUtility = _
  private var table: HTable = _

  override protected def beforeAll(): Unit = {
    super.beforeAll()
    utility = new HBaseTestingUtility()
    utility.startMiniCluster()
    // 建表,分配列族
    table = utility.createTable(
      "ip-profile".getBytes,
      Array(FAMILY_A.getBytes, FAMILY_B.getBytes)
    )
  }

  override protected def afterAll(): Unit = {
    super.afterAll()
    table.close()
    utility.shutdownMiniCluster()
  }

2.2 寫測試

  驗證一個寫入和讀出這個一般來說這一步意義不大,因為HBase裡面只有一種型別的資料——Bytes。如果使用的是HBase提供的一系列方法

byte[] Bytes.toBytes(long t);
byte[] Bytes.toBytes(int t);
byte[] Bytes.toBytes(byte t);
byte[] Bytes.toBytes(String t);

是不會有問題的。需要驗證的是在某個邏輯序列之後輸出到HBase的結果的驗證。但是由於這裡使用的是Mini cluster,具體操作上來說與普通的HBase表的put/get/delete並沒有差異。需要注意的是HTable的獲得不能夠再由conf檔案建立得到

HTable hTable = new HTable(conf, "tableName")

  如果之前有直接使用conf來獲得表的函式,在這裡需要進行拆分成類似於def ipGeographicQuery(hTable: HTable, ...)這樣的。要適應測試也是需要對程式碼進行一些修改的。剩下的就沒有什麼了,都是普通的操作。下面是一段沒有邏輯的程式碼:

val put = new Put(key)
put.add(col.family(), col.qualifier(),  ThriftSerde.serialize(u))
table.put(put)

val get = new Get(key)
get.add(col.family(), col.qualifier(), ThriftSerde.serialize(u))
val rs = table.put(get)
val thriftObj = new ThriftObj()
ThriftSerde.deserialize(thriftObj, rs.getValue(col.family(), col.qualifier()))

基本上意思就是,如果使用mini-cluster就沒有什麼需要專門為測試特殊處理的地方了。