2828use MongoDB \Laravel \Tests \Models \Soft ;
2929use MongoDB \Laravel \Tests \Models \SqlUser ;
3030use MongoDB \Laravel \Tests \Models \User ;
31+ use PHPUnit \Framework \Attributes \TestWith ;
3132
3233use function abs ;
3334use function array_keys ;
@@ -46,6 +47,7 @@ class ModelTest extends TestCase
4647{
4748 public function tearDown (): void
4849 {
50+ Carbon::setTestNow ();
4951 User::truncate ();
5052 Soft::truncate ();
5153 Book::truncate ();
@@ -1100,4 +1102,53 @@ public function testCreateOrFirstRequiresFilter()
11001102 $ this ->expectExceptionMessage ('You must provide attributes to check for duplicates ' );
11011103 User::createOrFirst ([]);
11021104 }
1105+ 1106+ #[TestWith([['_id ' => new ObjectID ()]])]
1107+ #[TestWith([['foo ' => 'bar ' ]])]
1108+ public function testUpdateOrCreate (array $ criteria )
1109+ {
1110+ // Insert data to ensure we filter on the correct criteria, and not getting
1111+ // the first document randomly.
1112+ User::insert ([
1113+ ['email ' => 'fixture@example.com ' ],
1114+ ['email ' => 'john.doe@example.com ' ],
1115+ ]);
1116+ 1117+ Carbon::setTestNow ('2010年01月01日 ' );
1118+ $ createdAt = Carbon::now ()->getTimestamp ();
1119+ 1120+ // Create
1121+ $ user = User::updateOrCreate (
1122+ $ criteria ,
1123+ ['email ' => 'john.doe@example.com ' , 'birthday ' => new DateTime ('1987年05月28日 ' )],
1124+ );
1125+ $ this ->assertInstanceOf (User::class, $ user );
1126+ $ this ->assertEquals ('john.doe@example.com ' , $ user ->email );
1127+ $ this ->assertEquals (new DateTime ('1987年05月28日 ' ), $ user ->birthday );
1128+ $ this ->assertEquals ($ createdAt , $ user ->created_at ->getTimestamp ());
1129+ $ this ->assertEquals ($ createdAt , $ user ->updated_at ->getTimestamp ());
1130+ 1131+ Carbon::setTestNow ('2010年02月01日 ' );
1132+ $ updatedAt = Carbon::now ()->getTimestamp ();
1133+ 1134+ // Update
1135+ $ user = User::updateOrCreate (
1136+ $ criteria ,
1137+ ['birthday ' => new DateTime ('1990年01月12日 ' ), 'foo ' => 'bar ' ],
1138+ );
1139+ 1140+ $ this ->assertInstanceOf (User::class, $ user );
1141+ $ this ->assertEquals ('john.doe@example.com ' , $ user ->email );
1142+ $ this ->assertEquals (new DateTime ('1990年01月12日 ' ), $ user ->birthday );
1143+ $ this ->assertEquals ($ createdAt , $ user ->created_at ->getTimestamp ());
1144+ $ this ->assertEquals ($ updatedAt , $ user ->updated_at ->getTimestamp ());
1145+ 1146+ // Stored data
1147+ $ checkUser = User::where ($ criteria )->first ();
1148+ $ this ->assertInstanceOf (User::class, $ checkUser );
1149+ $ this ->assertEquals ('john.doe@example.com ' , $ checkUser ->email );
1150+ $ this ->assertEquals (new DateTime ('1990年01月12日 ' ), $ checkUser ->birthday );
1151+ $ this ->assertEquals ($ createdAt , $ checkUser ->created_at ->getTimestamp ());
1152+ $ this ->assertEquals ($ updatedAt , $ checkUser ->updated_at ->getTimestamp ());
1153+ }
11031154}
0 commit comments