You will only obtain EVs if the opponent faints. If it flees or you run away, you will not get EVs. However, if multiple teamates partake in the battle they will both receive EVs. For example, if you encounter a wild Bellsprout with your Magicarp and switch out and defeat it with your Ninjask, both Magicarp and Ninjask will receive 1 Attack EV, which is Bellsprout's EV yield. The same goes if you were in a trainer battle. If you just ran away you would receive no EVs.