Unit test context for Uber Cadence activity

Issue

I am writing a unit test for cadence activity function which is using an UUID to retrieve a contact from the contact service. I wonder what context should I pass into cadence activity.

activity.Register(GetContactActivityFunc)

func GetContactActivityFunc(ctx context.Context, input ContactBbInput) (ContactBbOutput, error) {
   ...
}

This is testing function.

func TestGetContactActivityFunc(t *testing.T) {
    mockCSInterface := &mocks.Interface{}
    csClient := outbound.NewContactServiceClient(mockCSInterface)
    ctx := context.Background()
    ctx = context.WithValue(ctx, outbound.ContactServiceClientKey, csClient)
    contactUUID := contact.UUID("917801ab-36ff-4eea-8352-d6eafedb5106")
    bbInput := ContactBbInput{
        ContactID: &contactUUID,
    }
    bbOut, err := GetContactActivityFunc(ctx, bbInput)
    assert.NoError(t, err)
    assert.NotNil(t, bbOut.ContactObj)
}

The error message I got:

--- FAIL: TestGetContactActivityFunc (0.00s)
panic: getActivityEnv: Not an activity context [recovered]
    panic: getActivityEnv: Not an activity context

Solution

Use TestActivityEnvironment:

import (
    "go.uber.org/cadence/testsuite"
    "go.uber.org/cadence/worker" 
)

s := &testsuite.WorkflowTestSuite{} 
env := s.NewTestActivityEnvironment() 
// This is needed if ctx contains some external dependencies like
// database client
env.SetWorkerOptions(worker.Options{    
  BackgroundActivityContext: ctx, 
})
contact, err := env.ExecuteActivity(GetContactActivityFunc)

Make sure that the activity is registered through activity.Register.

Answered By – Maxim Fateev

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.