I've seen many people who asked this question. Even those who are religious have this question in mind as a big strange puzzle.
Everybody in this world has heard that we are here to experience the life and in the after life we either go to hell or heaven** based on what we did. But nobody knows why? Why do we need to be tested? Why do we have to experience this hardship and finally be punished or rewarded? What's the philosophy behind that?
The answer is in the story of Adam and Eve which is as old as human history. I don't care whether this story is true or just made up but I can see how tricky it is answering this question.
I know you all know this story but bear with me and read it just one more time.
"God created human and asked Lucifer who was one of his closest servants for a long time to respect and bow down in front of Adam as a human. Lucifer rejected. God said: What made you not to follow my order? He replied I am better. You made him from soil but I am from fire. God said: Go out of this holy place that you are so arrogant. Lucifer, realized the reason of asking to do so by God so he asked God to give him time so that he can pervert all human"
Now, God knew that Lucifer is so arrogant and he is not serving him sincerely. But can anybody judge a person for something he or she never did? He actually wanted to show Lucifer that he is not what he pretend. God could easily leave human free but all these things we are going through in our life is for one thing: Every person experiences those situations in which he or she is capable of swerving from the right way and because we have free will it's our choice which way to take, this is the best way to judge people as everything from their mind are disclosed during their life.
The question is why did he not created us all good hearted from the beginning?
The answer is, then free will which is the beauty of human would have no meaning in that case. Free will means you choose to sacrifice your money when you see a person is hungry and they can't afford their food. It doesn't mean you are free to do anything you like at enjoy to the most!
** Heaven or hell, I believe are in this earth rather than somewhere in the sky as many people think! It's the way you choose that makes your life a heaven or a hell.