The captain can be changed at any time during any game, provided he/she is one of the playing eleven (not a substitute player). The law doesn't recognise "farewell matches", so that is immaterial. Dhoni could have made Mohammad Shami the captain if he wanted to.
Quoting:
Law 1 (The players):
3. Captain
If at any time the captain is not available, a deputy shall act for
him.
...
(b) At any time after the nomination of the players, only a nominated
player can act as deputy in discharging the duties and
responsibilities of the captain as stated in these Laws.
The other answer has a lot of misinformation. It is not necessary that the vice-captain should take over. It usually happens, but the law does not require it.
Also, the captain's job is not just changing the field, as the other answer seems to imply. The laws are not even concerned with who changes the field.
Specific laws require the captain's involvement. Some examples (there are a lot more):
Law 2 (Substitutes and runners; batsman or fielder leaving the field; batsman retiring; batsman commencing innings)
9.Batsman retiring
...
(b) If a batsman retires for any reason other than as in (a) above, he
may resume his innings only with the consent of the opposing captain.
If for any reason he does not resume his innings it is to be recorded
as ‘Retired - out’.
...
Law 3: The umpires
2. Change of umpire
An umpire shall not be changed during the match, other than in
exceptional circumstances, unless he is injured or ill. If there has
to be a change of umpire, the replacement shall act only as striker’s
end umpire unless the captains agree that he should take full
responsibility as an umpire.
...
Law 5: The ball
4. New ball in match of more than one day’s duration
In a match of more than one day’s duration, the captain of the
fielding side may demand a new ball when the number of overs,
excluding any part overs, bowled with the old one is equal to or
greater than the prescribed number of overs. The Governing Body
responsible for the match concerned shall decide the number of overs
applicable in that match. This number shall not be less than 75 overs.