delete(); // 确保土地状态为空闲 $land = FarmLand::find($landId); $this->assertNotNull($land, '土地不存在'); // 设置土地为空闲状态 $land->status = LAND_STATUS::IDLE->value; $land->has_crop = false; $land->save(); // 确保种子配置存在 $seed = FarmSeed::where('item_id', $itemId)->first(); $this->assertNotNull($seed, '种子配置不存在'); // 模拟已存在的作物记录(这是bug的根源) $existingCrop = new FarmCrop(); $existingCrop->land_id = $landId; $existingCrop->user_id = $userId; $existingCrop->seed_id = $seed->id; $existingCrop->plant_time = now()->subHours(1); $existingCrop->growth_stage = GROWTH_STAGE::WITHERED; // 枯萎状态 $existingCrop->stage_start_time = now()->subHours(1); $existingCrop->stage_end_time = null; $existingCrop->disasters = []; $existingCrop->fertilized = false; $existingCrop->last_disaster_check_time = now()->subHours(1); $existingCrop->can_disaster = false; $existingCrop->save(); // 开启事务 DB::beginTransaction(); try { // 尝试种植新作物,应该失败 $result = CropService::plantCrop($userId, $landId, $itemId); // 验证种植失败 $this->assertNull($result, '种植应该失败,因为土地上已存在作物记录'); // 验证没有创建新的作物记录 $cropCount = FarmCrop::where('land_id', $landId)->count(); $this->assertEquals(1, $cropCount, '不应该创建新的作物记录'); DB::rollBack(); } catch (\Exception $e) { DB::rollBack(); // 验证抛出了正确的异常 $this->assertStringContainsString('土地上已存在作物', $e->getMessage()); } // 清理测试数据 FarmCrop::where('land_id', $landId)->delete(); } /** * 测试正常种植流程 */ public function test_normal_planting_works() { // 准备测试数据 $userId = 39077; // 使用现有用户 $landId = 296; // 使用现有土地 $itemId = 1; // 种子物品ID // 确保土地状态为空闲且没有作物 $land = FarmLand::find($landId); $this->assertNotNull($land, '土地不存在'); $land->status = LAND_STATUS::IDLE->value; $land->has_crop = false; $land->save(); // 清理可能存在的作物记录 FarmCrop::where('land_id', $landId)->delete(); // 确保种子配置存在 $seed = FarmSeed::where('item_id', $itemId)->first(); $this->assertNotNull($seed, '种子配置不存在'); // 开启事务 DB::beginTransaction(); try { // 尝试种植新作物,应该成功 $result = CropService::plantCrop($userId, $landId, $itemId); // 验证种植成功 $this->assertNotNull($result, '种植应该成功'); $this->assertArrayHasKey('crop', $result); $this->assertArrayHasKey('log_id', $result); // 验证创建了新的作物记录 $newCrop = FarmCrop::where('land_id', $landId)->first(); $this->assertNotNull($newCrop, '应该创建新的作物记录'); $this->assertEquals(GROWTH_STAGE::SEED->value, $newCrop->growth_stage->value); // 验证土地状态更新 $land->refresh(); $this->assertEquals(LAND_STATUS::PLANTING->value, $land->status); $this->assertTrue($land->has_crop); DB::rollBack(); } catch (\Exception $e) { DB::rollBack(); $this->fail('正常种植不应该失败: ' . $e->getMessage()); } // 清理测试数据 FarmCrop::where('land_id', $landId)->delete(); } }