2017-05-30 14 views
0

聲稱我有一些測試,取得了JSONObject的斷言,針對不同的端點返回,就像這樣:重用Junit的不同類別

JsonElement product = asJsonObject.get("product"); 
JsonElement type = product.getAsJsonObject().get("type"); 
Assert.assertEquals(ProductType.PRODUCT_1.name(), type.getAsString()); 
JsonElement name = product.getAsJsonObject().get("name"); 
Assert.assertEquals("name", name.getAsString()); 

大量的Java代碼,對不對?有多個端點返回相同的Json,我需要執行相同的斷言來保證預期的結果。

但我試圖找到一種方法來重用上面這段代碼。很顯然,我可以做這樣的事情:

new AssertProduct(asJsonObject.get("product")).assert(type, name); 

和:

class AssertProduct { 

    private JsonElement product; 

    AssertProduct(JsonElement product) { 
     this.product = product; 
    { 

    boolean assert(String name, String type) { 
     JsonElement type = product.getAsJsonObject().get("type"); 
     Assert.assertEquals(type, type.getAsString()); 
     JsonElement name = product.getAsJsonObject().get("name"); 
     Assert.assertEquals(name, name.getAsString()); 
    } 

} 

但是......這是對這類問題的好方法嗎?

+1

我將它們分開,所以你可以做'AssertProduct(asJsonObject.get(「product」)).ofType(x).ofName(y)' – vikingsteve

+1

恕我直言,這是一個很好的方法。 –

+0

@vikingsteve不錯。你願意對這個建議做出回答嗎?我會把你的問題標記爲已解決。 – Dherik

回答

1

這裏的斷言JSON對象的預期值以靈活的方式的基礎上,建造者模式:

public class AssertProduct { 

    private JsonElement product; 

    public AssertProduct(JsonElement product) { 
     this.product = product; 
    } 

    public static AssertProduct withProduct(JsonElement product) { 
     return new AssertProduct(product); 
    } 

    AssertProduct ofName(String name) { 
     Assert.assertEquals(name, product.getAsJsonObject().get("name").getAsString()); 
     return this; 
    } 

    AssertProduct ofType(String type) { 
     Assert.assertEquals(type, product.getAsJsonObject().get("type").getAsString()); 
     return this; 
    } 
} 

然後用法如下:

AssertProduct.withProduct(checkMe).ofName("some-name").ofType("some-type");