The answer is: yes. Thus, a person may testify in favor of his enemy with the intention of warding off his harm. For this reason, his testimony is accepted neither in favor of his enemy nor against him.
In any case, although this reasoning is plausible, it is open to some consideration. We say: the possibility that he may testify in favor of his enemy out of undue favor or to avert harm is remote, even though it may occur. Mere rational possibilities are not taken into account in such theoretical and practical matters. Otherwise, we could say that even upright witnesses, in whom there are no disqualifying factors, may err, may forget, or may develop enmity toward the person against whom they are testifying.
If a friend testifies for his friend, is his testimony accepted? If we were to say that a friend’s testimony for his friend is not accepted, we would be telling people: “Do not become friends with one another, for a friend’s testimony for his friend is not accepted!” This is problematic, because it would mean encouraging people not to form friendships—something no one could reasonably maintain. Therefore, some scholars, including Ibn Aqil, one of the followers of Imam Ahmad—may Allah have mercy on him—held that if a friendship is so strong that it reaches the level of passionate attachment or something similar, then his testimony in favor of his friend is not accepted. This is by reverse analogy with the testimony of an enemy against his enemy: an enemy has no bond with his enemy, whereas an intimate friend, whose friendship is intense, has a strong bond with his friend. Some people, when it comes to their friends, forget everything and do not hesitate to testify falsely for them; they are unconcerned about it, especially when the matter reaches the level of passionate attachment. This analogy is very strong. As for the ordinary friendship commonly found among people, there is no doubt that it is not a disqualifying factor.