Unbounded Fredholms operators
The equality holds for closed unbounded operators, provided one interprets "cokernel" as "quotient by the closure of the image".
You can check it directly for closed self-adjoint operators by using the spectral theorem (i.e. check it for multiplication operators on $L^2(X)$ for some measure space $X$). Then use polar decomposition to reduce the case of an arbitrary closed operator to that of a self-adjoint operator.
PS: this has nothing to do with the operator being Fredholm or not.