This is covered by Law 16 "The result" and in particular Law 16.1:
The side which has scored a total of runs in excess of that scored in the two completed innings of the opposing side shall win the match.
This means a win can be achieved in one of three ways:
- The team batting in the fourth innings reaches a point at which they have scored more runs across their two innings than the opposing side scored in their two completed innnings. The team batting wins.
- The team batting in the fourth innings loses all their wickets before they have scored as many runs as the opposing side scored in their two completed innnings. The team batting loses.
- One team scores more runs in its one completed innings than the opposing side scores in both its completed innings. That side wins "by an innings".
A tie occurs if both sides have an exactly equal number of runs at the conclusion of the fourth innings (16.5.1):
The result of a match shall be a Tie when all innings have been completed and the scores are equal.
and anything else is a draw:
The result of a match shall be a Draw when it is not determined in any of the ways stated in 16.1, 16.2, 16.3, 16.4 or 16.5.1.
(16.2 refers to one-innings matches so is not applicable to test matches, 16.3 refers to umpires awarding a match and 16.4 refers to agreements to alter the result conditions; no such agreement exists in the standard ICC Test Match playing conditions).