golang单元测试AWS会话或Emr服务

时间:2019-11-03 22:29:23

标签: unit-testing aws-sdk-go

我写了一个代码,该代码将根据集群ID打印EMR集群状态。但是在进行单元测试时我很难过。

emrinterface.EMR:

type EMR struct {
    Client emriface.EMRAPI
}

func NewEMR() *EMR {
    sess := session.CreateNewSession()
    return &EMR{
        Client: emr.New(sess),
    }
}

根据群集ID打印群集状态:

func GetClusterStatus(e entities.Cluster) (string, error) {
    clusterID := ClusterID(e)

    emrService := emrinterface.NewEMR()
    clusterDetails, err := emrService.Client.DescribeCluster(&emr.DescribeClusterInput{
        ClusterId: clusterID})
    if err != nil {
        return "error", err
    }

    clusterStatus := *clusterDetails.Cluster.Status.State

    return fmt.Sprintf(clusterStatus), nil
}

主要

func main() {
    lambda.Start(GetClusterStatus)
}

单元测试:

func setup() *emrtestutils.MockEMR {
    return &emrtestutils.MockEMR{}
}

func TestGetClusterStatus(t *testing.T) {
    testCases := []struct {
        entities.Cluster
        status string
        err    error
    }{
        {entities.Cluster{ClusterID: "j-dfdslkj3kl213kj"}, "STARTING", nil},
    }

    for _, testCase := range testCases {
        mockEMR := setup()
        mockEMR.On("MockEMRDescribeCluster",
        &emr.DescribeClusterInput{
        ClusterId: aws.String("jdfdslkj3kl213kj")}).Return("STARTING", testCase.err)
        res, err := GetClusterStatus(testCase.Cluster)
        fmt.Println(err)
        assert.Equal(t, res, testCase.status)
    }
}

0 个答案:

没有答案