Why should we pray to God when he knows what we need and if he answers in his time and in his way? Also, if God is an all-knowing God he would definitely know that Job would not lose his faith in him. Then why did he allow Job to be tested?
We should pray to God for a few reasons. First of all, because he is God and he has asked us to pray. That is reason enough.
Second, because God wants a relationship with us. A relationship involves communication. God speaks to us through his Scripture, through the life and ministry of Jesus and also through the work of the Holy Spirit on our lives, who “guides us into all truth” and who “convicts us with regard to sin.” (John 14:25-27 and John 16:7-11). But any relationship, by definition, is two-way. Prayer may not be the only way we can speak to God, but it certainly is the main one. In prayer, we talk to God, and he hears us.
Now, you are right that when we share our thoughts, aspirations and requests with God, we are not telling him anything he does not already know, but God is like a father (or mother). He wants us to express our desires, fears and thoughts with him because he loves us and he wants us to express our love for him in prayer.
Pray is principally of benefit to ourselves. We need to pray as much or more than God needs us to pray–especially because, as you seem to notice, we are not giving new information to God when we pray. It is when we pray that we express our love for him and confirm to ourselves as well that we love him.
As for your second question, if I understand God’s foreknowledge correctly, you are right that God knew what Job would do before he allowed Job to be tempted by his suffering. For us, having foreknowledge would “spoil” everything. Right! It is like a movie for which if we knew the ending, it would spoil the movie. We view time in a linear fashion. There are the past, the present and the future. God does not view reality this way. He exists outside of time. For God, foreknowledge is natural. Nevertheless, this does not mean that he does not want a relationship with us, and that relationship includes prayer.
God did not learn anything he did not already know when he allowed Satan to tempt him, but Job definitely learned something, as did his friends, and as do we! There is great benefit derived from the testing of Job. His is the ultimate example for us of what it means to put our faith and trust in God, no matter the circumstances. Job had a great, powerful and effective life because of what he suffered. We can see that Job learned much from the encounter with God in Job 42:1-6. God uses Job as inspiration for us as well. Also, Job glorified God through his faith in Him. There are many reasons that I can think of that God allowed Job to be tested, but none of them benefit God. They benefit us. Well, actually, I take that back, because, like I said, Job gave glory to God and that is something that pleases God.