Test helper method in workflow code

I have a use case similar to the example above. How can I unit test such a method?
The main issue is the inability to create a workflow context of my own

Use TestWorkflowEnvironment to test workflows or any part of the workflow.

@maxim, Do you mean by invoking it using the ExecuteWorkflow method? Would it work if it was a struct method instead?

Yes, it will work with the struct method as well. Another approach is to create an anonymous lambda which is registered with the TestWorkflowEnvironment and add all unit test-specific workflow code there.

	wFn := func(ctx workflow.Context) error {
        	// Any unit test specific initialization code
            return SendErrorResponse(...);
	}
	wfEnv = s.NewTestWorkflowEnvironment()
	wfEnv.RegisterWorkflow(wFn)
	wfEnv.ExecuteWorkflow(wFn)

Hi @maxim , when I test a workflow struct method that invokes an activity, the test expects the struct method to set activity options to the context. However, the context is set in a different method that invokes the struct method.
It feels odd to add set activity context to every struct method solely for testing purposes. If my struct method does not invoke an activity, the issue is not seen.
Please correct me if I am wrong.

You are correct. You can create your wrapper around TestEnvironment that does create the correct context.

Thanks, Maxim, that makes sense. Another question regarding testing of a struct method. If my struct method takes an error as an input, the test for this struct method fails as it can not decode a variable of error type. I want to avoid propagating the error as a struct variable. Is there any workaround for this or would you recommend I pass the error as a struct variable?

Context -
I have a workflow struct that has workflow methods for invoking activities.

type workflow struct {
	output string
}

func (w *workflow) method1(ctx workflow.context) error {
	future := workflow.ExecuteActivity(ctx, "activityName")
	return future.Get(ctx, &w.output)
}
func (w *workflow) compensate(ctx workflow.Context, err error) error {
	future := workflow.ExecuteActivity(ctx, "compensateActivityName")
	compensateErr := future.Get(ctx, nil)
	if compensateErr != nil {
		err = multiErrors.Append(err, compensateErr)
	}
	return err
}

and I want to test the compensate method

	wFn := func(ctx workflow.Context) error {
        	w := &workflow{}
        	return w.compensate(ctx, fmt.Errorf(...))
	}
	wfEnv = s.NewTestWorkflowEnvironment()
	wfEnv.RegisterWorkflow(wFn)
	wfEnv.ExecuteWorkflow(wFn)
1 Like