O ye who believe! Allah doth but make a trial of you in a little matter of game well within reach of game well within reach of your hands and your lances, that He may test who feareth him unseen: any who transgress thereafter, will have a grievous penalty.
Elsewhere (67:2), the Holy Quran mentions:
Who created death and life that He might try you as to which of you is better in deed. He is the Most Mighty, the Most Forgiving:
Commenting on this verse, Maududi writes,
“That is, the object of giving life to man in the world and causing his death is to test him to see which of them is best in deeds. Allusion has been made in this brief sentence to a number of truths: (1) That life and death are given by Allah, no one else can grant life nor cause death. (2) That neither the life nor the death of a creation like man, which has been given the power to do both good and evil, is purposeless. The Creator has created him in the world for the test. Life is for him the period of the test and death means that the time has come to an end. (3) That for the sake of this very test the Creator has given every man an opportunity for action, so that he may do good or evil in the world and practically show what kind of a man he is. (4) That the Creator alone will decide who has done good or evil. It is not for us to propose a criterion for the good and the evil deeds but for Almighty Allah. Therefore, whoever desires to get through the test, will have to find out what is the criterion of a good deed in His sight. Every person will be recompensed according to his deeds, for if there was no reward or punishment the test would be meaningless.” (Tafhim ul Quran, Surah 67 verse 2 note # 4)
The Holy Quran also mentions in 51:56,
I have only created Jinns and men, that they may serve Me.
The Prophet (peace be upon him) explained this verse as follows:
It is related by Umar Ibn al-Khattab (RA) that he heard the Messenger of Allah (saw) say: “The actions are but judged according to intentions; and to every man is due what he intended. Thus, whosoever migrates for the sake of Allah and His Messenger [and there is no other motive of his migration except compliance with the commands of Allah and the Prophet and winning of their good pleasure], his migration is accounted for the sake of Allah and His messenger [and, doubtlessly, he is a true Muhajir-Emigrant]-and shall receive the recompense prescribed for Hijrat-Migration- towards Allah and His Messenger]; and whosoever migrates for the sake of this world or to wed a woman [his migration will not be for Allah and the Prophet], and it will be accounted only for the purpose for which it is intented.” (Bukhari and Muslim) [taken from Maariful Hadith, Noomani]
For details, see the following post: Actions are by Intentions
Maududi, Abul Ala (2010). Tafhim ul Quran. (surah 67, verse 2, note 4). https://www.englishtafsir.com/Quran/27/index.html