我正在使用 client-go(go 的 k8s 客户端)以编程方式从集群中检索和更新一些秘密。在这样做时,我面临着对我的代码进行单元测试的需要,经过一番调查,我偶然发现了 client-go 的fake客户端。但是,我还不能模拟错误。我已按照此问题的说明进行操作,但没有成功。这里有我的业务逻辑:func (g goClientRefresher) RefreshNamespace(ctx context.Context, namespace string) (err error, warnings bool) { client := g.kubeClient.CoreV1().Secrets(namespace) secrets, err := client.List(ctx, metav1.ListOptions{LabelSelector: "mutated-by=confidant"}) if err != nil { return fmt.Errorf("unable to fetch secrets from cluster: %w", err), false } for _, secret := range secrets.Items { // business logic here } return nil, warnings}和测试:func TestWhenItsNotPossibleToFetchTheSecrets_ThenAnErrorIsReturned(t *testing.T) { kubeClient := getKubeClient() kubeClient.CoreV1().(*fakecorev1.FakeCoreV1). PrependReactor("list", "secret", func(action testingk8s.Action) (handled bool, ret runtime.Object, err error) { return true, &v1.SecretList{}, errors.New("error listing secrets") }) r := getRefresher(kubeClient) err, warnings := r.RefreshNamespace(context.Background(), "target-ns") require.Error(t, err, "an error should have been raised")}但是,当我运行测试时出现nil错误。难道我做错了什么?
1 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
我终于找到了错误......它在反应堆函数的资源名称中,我有secret,它应该是复数secrets......:facepalm:。所以这是代码的正确版本:
func TestWhenItsNotPossibleToFetchTheSecrets_ThenAnErrorIsReturned(t *testing.T) {
kubeClient := getKubeClient()
kubeClient.CoreV1().(*fakecorev1.FakeCoreV1).
PrependReactor("list", "secrets", func(action testingk8s.Action) (handled bool, ret runtime.Object, err error) {
return true, &v1.SecretList{}, errors.New("error listing secrets")
})
// ...
}
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消