create(); // 创建测试土地 $land = FarmLand::factory()->create([ 'user_id' => $user->id, 'status' => 3, // DISASTER状态 ]); // 创建测试作物(带有干旱灾害) $crop = FarmCrop::factory()->create([ 'land_id' => $land->id, 'user_id' => $user->id, 'disasters' => [ [ 'type' => 1, // 干旱 'status' => 'active', 'start_time' => now()->timestamp, 'penalty' => 0.05 ] ] ]); // 创建浇水道具 $wateringItem = \App\Module\GameItems\Models\Item::factory()->create([ 'fram_drought_rate' => 100 // 100%成功率 ]); // 给用户添加浇水道具 ItemService::addItem($user->id, $wateringItem->id, 1); // 清空缓存,确保测试环境干净 Cache::flush(); // 模拟浇水请求 $response = $this->actingAs($user) ->postJson('/api/land/watering', [ 'land_id' => $land->id, 'item_id' => $wateringItem->id ]); // 验证响应成功 $response->assertStatus(200); // 验证响应中包含LastData $responseData = $response->json(); $this->assertArrayHasKey('last_data', $responseData); // 验证LastData中包含lands信息 $lastData = $responseData['last_data']; $this->assertArrayHasKey('lands', $lastData); $this->assertNotEmpty($lastData['lands']); // 验证土地信息正确 $landData = collect($lastData['lands'])->firstWhere('id', $land->id); $this->assertNotNull($landData); // 验证灾害状态已更新 $this->assertFalse($landData['need_watering'] ?? true); // 验证数据库中的灾害状态已更新 $crop->refresh(); $disasters = $crop->disasters ?? []; $droughtDisaster = collect($disasters)->firstWhere('type', 1); $this->assertEquals('cleared', $droughtDisaster['status'] ?? 'active'); } /** * 测试浇水失败时的响应 */ public function testWateringFailureResponse() { // 创建测试用户 $user = User::factory()->create(); // 创建测试土地 $land = FarmLand::factory()->create([ 'user_id' => $user->id, 'status' => 3, // DISASTER状态 ]); // 创建测试作物(带有干旱灾害) $crop = FarmCrop::factory()->create([ 'land_id' => $land->id, 'user_id' => $user->id, 'disasters' => [ [ 'type' => 1, // 干旱 'status' => 'active', 'start_time' => now()->timestamp, 'penalty' => 0.05 ] ] ]); // 创建浇水道具(低成功率) $wateringItem = \App\Module\GameItems\Models\Item::factory()->create([ 'fram_drought_rate' => 0 // 0%成功率,确保失败 ]); // 给用户添加浇水道具 ItemService::addItem($user->id, $wateringItem->id, 1); // 清空缓存,确保测试环境干净 Cache::flush(); // 模拟浇水请求 $response = $this->actingAs($user) ->postJson('/api/land/watering', [ 'land_id' => $land->id, 'item_id' => $wateringItem->id ]); // 验证响应失败 $response->assertStatus(400); // 验证错误消息 $responseData = $response->json(); $this->assertStringContains('浇水失败', $responseData['msg'] ?? ''); } }