我想用phpunit和laravel测试上传图片过程。 我在控制器中的功能如下:
public function store(Request $request){
$validator = Validator::make($request->all() , [
'name' => 'required|string|max:300',
'icon' => 'nullable|image'
]);
if($validator->fails()){
return response()->json([
'status' => 422,
'message' => 'validation_error_occurred',
'entire' => [
'errors' => $validator->errors()->all()
]
] , 422);
}
$category = new StoreCategory();
$category->name = $request->name;
if($request->hasFile('icon')){
$imgName = uniqid() . '.' . $request->icon->getClientOriginalExtension();
$request->icon->move(public_path('/store-categories-image') , $imgName);
$category->icon = $imgName;
}
$category->save();
return response()->json([
'status' => 200,
'message' => 'category_stored' ,
'entire' => [
'category' => $category
]
] , 200);
}
我的phpunit测试如下:
public function testSaveCategory(){
$admin = factory(Admin::class)->create();
$token = $admin->createToken('loginToken')->accessToken;
$category = factory(StoreCategory::class)->create();
$this->json('POST' , '/admin-api/store-category' , [
'name' => $category->name,
'icon' => UploadedFile::fake()->image('icon.png')
] , [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
])
->assertStatus(200)
->assertJson([
'status' => 200,
'message' => 'category_stored',
])
->assertJsonStructure([
'entire' => [
'category' => ['id' , 'icon' , 'name' , 'deleted' , 'created_at' , 'updated_at']
]
]);
}
但是,当我在命令行中运行phpunit
命令时,测试失败并得到以下消息:
Excepted status code 200 but received 500.
当我在邮递员中运行我的api时,它成功返回状态200。
出什么问题了?