简体   繁体   English

断言:模拟:我不知道要返回什么(即使我已经声明了模拟 function 和返回)

[英]assert: mock: I don't know what to return (even if I've declared the mock function & the return)

I use Testify to create a unit test for my golang app.我使用 Testify 为我的 golang 应用程序创建单元测试。 I need to create a unit test for this function where it calls a variadic function (function with trailing arguments).我需要为此 function 创建一个单元测试,它调用可变参数 function (带有尾随参数的函数)。 I encountered an error when I test it.我在测试时遇到了错误。 I'm actually not sure if the error is because of the trailing argument itself or not, but I feel like there's something wrong with the mock.我实际上不确定错误是否是由于尾随参数本身造成的,但我觉得模拟有问题。

// svc/callThisFunction.go
// data type of args is []sqkit.SelectOption
func CallThisFunction(ctx context.Context, args ...sqkit.SelectFunctiom) (result string, err error) {
  return result, nil
}

// svc/functionToTest.go
// This is the function that I wanna test
func FunctionToTest(ctx context.Context, id int64) (result string, err error) {
  args := []sqkit.SelectOption{
    sqkit.Where{
      fmt.Sprintf("id = %d", id),
    },
  }

  newResult, err := callThisFunctionService.CallThisFunction(ctx, args)
  if err != nil {
    return newResult, err
  }

  return newResult, nil
}
// svc/functionToTest_test.go

func Test_FunctionToTest(t *testing.T) {
  testCase := []struct {
    name string
    id int64
    onCallThisFunctionMock func(callThisFunctionSvc *mocks.CallThisFunctionSvc)
    expectedResult string
    wantError bool
    expectedError error  
  }{
      {
        name: "Success",
        id: 1,
        onCallThisFunctionMock: func(callThisFunctionSvc *mocks.CallThisFunctionSvc) {
          // NOTE: I've created 2 different versions (used separately, not at the same), using mock.Anything() and using actual arguments
          // Both of these give the same errors
          // Using actual arguments          
          args := []sqkit.SelectOption{
            sqkit.Where{
              fmt.Sprintf("id = %d", 1},
            },
          }
          callThisFunctionSvc.On("CallThisFunction", context.Background(), args).Return("Success", nil)

          // Using mock.Anything
          callThisFunctionSvc.On("CallThisFunction", context.Background(), mock.Anything).Return("Success", nil)
        }
      }
   }

   for _, tc := range testCases {
     var callThisFunctionSvc = new(mocks.CallThisFunctionSvc)

     tc.onCallThisFunctionMock(callThisFunctionSvc)

     svc := &svc.FunctionToTest{
       CallThisFunction: callThisFunctionSvc,
     }

     actualResult, actualError := svc.FunctionToTest(context.Background(), tc.id)

     if tc.wantEror {
       require.Error(t, actualError, tc.expectedError)
     } else {
       require.NoError(t, actualError)
     }

     require.Equal(t, tc.expectedResult, actualResult)
   }
}

This is the error it gives这是它给出的错误

=== RUN   Test_GenerateDocument
--- FAIL: Test_GenerateDocument (0.00s)
panic: 
assert: mock: I don't know what to return because the method call was unexpected.
        Either do Mock.On("CallThisFunction").Return(...) first, or remove the GetTemplates() call.
        This method was unexpected:
                CallThisFunction(*context.emptyCtx,sqkit.Where)
                0: (*context.emptyCtx)(0xc0000a4010)
                1: sqkit.Where{"id = 1"}

Usually, when I encountered an error like this, it's because I haven't defined the return values of the function calls inside the function I wanna test.通常,当我遇到这样的错误时,是因为我没有在我想测试的 function 中定义 function 调用的返回值。 But this time I've created it, but it somehow can't read the return.但是这次我已经创建了它,但它不知何故无法读取返回值。 Any idea why?知道为什么吗?

The error indicates you called CallThisFuncion with params (context.Context, sqkit.Where) , but your example is using and setting the expectation for (context.Context, []sqkit.Option) .该错误表明您使用参数(context.Context, sqkit.Where)调用了CallThisFuncion ,但您的示例正在使用并设置(context.Context, []sqkit.Option)的期望。 The example with mock.Anything should work, but I believe it's failing because of the context. mock.Anything的示例应该可以工作,但我相信它会因为上下文而失败。 You'll need to set the expectation with the same context you're passing down.您需要使用您传递的相同上下文设置期望。 If FunctionToTest is going to be altering the context, I believe you'll need to use mock.Anything instead.如果FunctionToTest要改变上下文,我相信你需要使用mock.Anything代替。

func Test_FunctionToTest(t *testing.T) {
  testCase := []struct {
    name string
    id int64
    onCallThisFunctionMock func(context.Context, *mocks.CallThisFunctionSvc)
    expectedResult string
    wantError bool
    expectedError error  
  }{
      {
        name: "Success",
        id: 1,
        onCallThisFunctionMock: func(ctx context.Context, callThisFunctionSvc *mocks.CallThisFunctionSvc) {
          args := []sqkit.SelectOption{
            sqkit.Where{
              fmt.Sprintf("id = %d", 1},
            },
          }
          callThisFunctionSvc.On("CallThisFunction", ctx, args).Return("Success", nil)
        }
      }
  }

  for _, tc := range testCases {
    var callThisFunctionSvc = new(mocks.CallThisFunctionSvc)
    var ctx = context.Background()

    tc.onCallThisFunctionMock(ctx, callThisFunctionSvc)

    svc := &svc.FunctionToTest{
      CallThisFunction: callThisFunctionSvc,
    }

    actualResult, actualError := svc.FunctionToTest(ctx, tc.id)

    if tc.wantEror {
      require.Error(t, actualError, tc.expectedError)
    } else {
      require.NoError(t, actualError)
    }

    require.Equal(t, tc.expectedResult, actualResult)
  }
}

If you want to ensure a context.Context was passed as the first parameter but don't care what context, you could use AnythingOfType .如果您想确保context.Context作为第一个参数传递但不关心什么上下文,您可以使用AnythingOfType

callThisFunctionSvc.On("CallThisFunction", mock.AnythingOfType("context.Context"), args).Return("Success", nil)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 assert: mock: 我不知道要返回什么,因为方法调用出乎意料 - assert: mock: I don't know what to return because the method call was unexpected assert: mock: I don't know what to return because the method call was unexpected Error while writing unit test in Go 断言:模拟:我不知道要返回什么,因为方法调用是意外的 Error while writing unit test in Go - assert: mock: I don't know what to return because the method call was unexpected Error while writing unit test in Go 如何模拟构造函数 function 的链式 function 的返回值? - How can I mock return value of chained function of a constructor function? 如何模拟类的函数的返回值? - How do I mock a class's function's return value? 我如何在开玩笑的模拟功能内返回模拟? - How do I return mocks within a mock function in jest? 模拟函数,在玩笑中返回模拟值 - mock function with return mock value in jest 如何监视一个函数并使用茉莉花从另一个函数内部返回模拟值? - How can I spy on a function and return a mock value from inside another function using jasmine? 如何在测试期间模拟 vt vue-i18n 指令以返回密钥 - how to mock v-t vue-i18n directive to return key during testing 谷歌模拟-一个(独立)函数的模拟返回值称为 - google mock - mock return value of a (free-standing) function called 如何模拟Nodes网络库函数的返回值? - How can I mock the return value of Nodes net library functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM