For example: "If I didn't know any better, I'd say you were having a good time" This is apparent by the context that the person is having a great time, but why say If I didn't know any better?
It can be said sarcastically, or it can be said sincerely.
Say a friend wants to bring another friend to a gathering. The other friend is reluctant to go, and has to be dragged along.
"If I didn't know any better, I'd say you were having a good time," means, I told you you'd like it! It's a humorous statement. This is probably it's most common use.
Say someone is really unhappy but has an obligation to go to a gathering, and takes a good friend for support. The person is doing their best to be social, but the only one who isn't fooled is the good friend. The good friend may be telling the reluctant participant that they're doing a good job.
The expression is using irony for a dry humorous effect.
In the example you give, what we're really meaning is 'It's apparent to me that you're having a good time'.
What the phrase literally says is 'It appears that you're having a good time, but I have better knowledge that says that you're not'. Which isn't what we mean; we're making a joke - it's so clear that you're having a good time, that we pretend that you're not, as to highlight how a good a time that you really are having.
Consider a different example, let's say you're observing an expert woodchopper, and their performance is very impressive.
You can say, 'If I didn't know any better, I'd say you're an expert at this'. The reason it's funny, and not offense to the subject, to suggest that they're not really an expert, is because it's so clearly obvious that they're an expert.
I should add, that the joke is more effective when the skill/attribute in question is something of a surprise. For example, it wouldn't be that funny to say 'If I didn't know any better, I'd say you're really good at this' to a professional chef, because the doubting of their ability was never plausible.
Most of the time it is to imply that the opposite is true.
If I didn't know any better, I’d say X was true - this means X is NOT true (because in reality you know better.)
e.g. If I didn’t know any better, I’d say they were twin sisters. The truth is that they are NOT twin sisters because you know perfectly well that they are not, but maybe they look a lot alike etc.