How to properly create mocks for functions in Go when unit testing?
Hello! I started learning Go and trying to write unit tests for my project. I encountered a problem: I have a function that calls an external service (for example, sends an email or makes an HTTP request). In tests, I don't want to actually call these services, so I need to create a mock.
Here's a simplified example of my code:
```go
package main
import (
"fmt"
"net/smtp"
)
type EmailSender struct{}
func (e *EmailSender) SendEmail(to, subject, body string) error {
// Actual email sending via SMTP
err := smtp.SendMail("smtp.example.com:587", nil, "from@example.com", []string{to}, []byte(body))
if err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
return nil
}
func NotifyUser(sender *EmailSender, userEmail string) e
No answers yet.
Log in to leave an answer
Blogs