2017-03-07 16 views
10

मैं एक यूनिट टेस्ट बना रहा हूं और प्रतिक्रिया में लौटाई गई JSON संरचना का परीक्षण करना चाहता हूं। मुझे पता है कि TestResponse आपकी JSON प्रतिक्रिया की संरचना से मेल खाने के लिए assertJsonStructure विधि प्रदान करता है। लेकिन किसी कारण से मैं $structure को मेरी प्रतिक्रिया में मैप करने में असमर्थ हूं और नतीजतन परीक्षण विफल रहता है। मुझे आवश्यक स्निपेट साझा करने दें।PhpUnit टेस्ट में जेसनस्ट्रक्चर मैच - लार्वेल 5.4

Endpoint रिस्पांस

{ 
    "status": true, 
    "message": "", 
    "data": [ 
     { 
      "id": 2, 
      "name": "Shanelle Goodwin", 
      "email": "[email protected]net", 
      "created_at": "2017-03-05 16:12:49", 
      "updated_at": "2017-03-05 16:12:49", 
      "user_id": 1 
     } 
    ] 
} 

टेस्ट समारोह

public function testEndpoint(){ 

    $response = $this->get('/api/manufacturer/read', [], $this->headers); 
    $response->assertStatus(200); 
    $response->assertJsonStructure([ 
    'status', 
    'message', 
    'data' => [ 
     { 
     'id', 
     'name', 
     'email', 
     'created_at', 
     'updated_at', 
     'user_id' 
     } 
    ] 
    ]); 
    var_dump("'/api/manufacturer/read' => Test Endpoint"); 
} 

वहाँ कर सकते हैं data सरणी में कई नोड्स इतना है कि मैं क्यों संरचना में सरणी का उल्लेख करने की कोशिश की लेकिन यह नहीं करता है 'लगता है टी सही ढंग से नक्शा। किसी भी मदद की सराहना की जाएगी :-)

उत्तर

13

सौभाग्य से, विभिन्न विकल्पों के साथ खेलना मैंने इस मुद्दे को हल किया है। अगर हम किसी सरणी में नेस्टेड ऑब्जेक्ट से मेल खाते हैं तो एक '*' कुंजी के रूप में अपेक्षित है। हम यहां संदर्भ देख सकते हैं।

Source: TestResponse - Line # 363

मैं array of objects`

$response->assertJsonStructure([ 
    'status', 
    'message', 
    'data' => [ 
     '*' => [ 
     'id', 
     'name', 
     'email', 
     'created_at', 
     'updated_at', 
     'user_id' 
     ] 
    ] 
    ]); 

के लिए इस तरह की संरचना की स्थापना की और है तो आप सिर्फ एक वस्तु

$response->assertJsonStructure([ 
    'status', 
    'message', 
    'data' => [ 
     [ 
     'id', 
     'name', 
     'email', 
     'created_at', 
     'updated_at', 
     'user_id' 
     ] 
    ] 
    ]); 
+1

बेहद उपयोगी! आधिकारिक दस्तावेज़ों में होना चाहिए। हमारे लिए इसे मछली पकड़ने के लिए धन्यवाद। –

+1

मेरा नायक, धन्यवाद –

+0

[कोड स्थानांतरित हो गया है] (https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Testing/TestResponse.php#L363) –

1

मुझे लगता है कि आपको इसका उपयोग करना चाहिए:

$response->assertJsonStructure([ 
    'status', 
    'message', 
    'data' => [ 
     [ // change here 
     'id', 
     'name', 
     'email', 
     'created_at', 
     'updated_at', 
     'user_id' 
     ] // change here 
    ] 
    ]); 
+0

आप ठीक कह रहे हैं, लेकिन यह एक से मेल खाता है मिलान करना चाहते हैं 'डेटा' सरणी में एकल वस्तु। मैंने इस मुद्दे को हल किया और इसे नीचे पोस्ट किया। धन्यवाद –

संबंधित मुद्दे