Testing
When writing unit tests for your application, you typically don't want to hit the real Conviso API.
Using Interfaces
The recommended approach is to define an interface in your application that covers the SDK methods you use. This allows you to create a mock implementation for tests.
// myapp/service.go
// 1. Define an interface
type CDPClient interface {
Identify(ctx context.Context, userID string, traits map[string]interface{}) error
Track(ctx context.Context, userID string, eventName string, properties map[string]interface{}) error
}
type MyService struct {
cdp CDPClient
}
func NewMyService(cdp CDPClient) *MyService {
return &MyService{cdp: cdp}
}
func (s *MyService) OnSignup(userID string) {
s.cdp.Track(context.Background(), userID, "signup", nil)
}
Creating a Mock
In your tests, implement a mock.
// myapp/service_test.go
type MockCDP struct {
TrackCalls []string
}
func (m *MockCDP) Identify(ctx context.Context, userID string, traits map[string]interface{}) error {
return nil
}
func (m *MockCDP) Track(ctx context.Context, userID string, eventName string, props map[string]interface{}) error {
m.TrackCalls = append(m.TrackCalls, userID+":"+eventName)
return nil
}
func TestSignup(t *testing.T) {
mock := &MockCDP{}
service := NewMyService(mock)
service.OnSignup("user_123")
if len(mock.TrackCalls) != 1 {
t.Errorf("Expected 1 track call, got %d", len(mock.TrackCalls))
}
}
Integration Testing
If you want to perform integration tests against code that uses the real SDK *cdp.Client struct (which doesn't implement your interface, or if you want to test the wrapper itself), you can use httptest to mock the Conviso HTTP API.
func TestRealClientInteraction(t *testing.T) {
// Start a local test server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/persons/identify" {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusNotFound)
}))
defer server.Close()
// Configure client to point to test server
client := cdp.NewClient(cdp.CDPConfig{
CDPAPIKey: "test",
CDPEndpoint: server.URL, // Point to local mock
})
err := client.Identify(context.Background(), "u1", nil)
if err != nil {
t.Error("Expected success")
}
}