io.mockk.MockKException:找不到以下内容的答案:SavedStateHandle(#1).set(Key,Something)

时间:2020-04-11 03:49:44

标签: kotlin mockk viewmodel-savedstate

我有一个如下的ViewModel类(简化以演示我遇到的问题)

public static void GitFetch()
    {
        string USERNAME = "myusername";
        string PASSWORD = "mypassword";

        string logMessage = "";
        using (var repo = new Repository(@"D:\GitHub\my-test-repo"))
        {
            FetchOptions options = new FetchOptions();
            options.CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) =>
                new UsernamePasswordCredentials()
                {
                    Username = USERNAME,
                    Password = PASSWORD
                });

            foreach (Remote remote in repo.Network.Remotes)
            {
                IEnumerable<string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification);
                Commands.Fetch(repo, remote.Name, refSpecs, options, logMessage);
            }
        }
        Console.WriteLine(logMessage);
    }

我有一个如下的MockK测试班

class MyViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
    init {
        savedStateHandle.set(KEY, "Something")
    }
}

通过运行测试,我得到以下错误

@Test
fun `test something simple`() {
    val savedStateHandle = mockk<SavedStateHandle>()
    val viewModel = MyViewModel(savedStateHandle)
    verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}

我想我也需要为io.mockk.MockKException: no answer found for: SavedStateHandle(#1).set(Key, Something) 处理set。我该如何在SavedStateHandle中这样做?

1 个答案:

答案 0 :(得分:5)

好像我需要relaxed = true到我的Mock,使其只返回默认值。

@Test
fun `test something simple`() {
    val savedStateHandle = mockk<SavedStateHandle>(relaxed = true)
    val viewModel = MyViewModel(savedStateHandle)
    verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}

另一个选择是模拟返回值...

@Test
fun `test something simple`() {
    val savedStateHandle = mockk<SavedStateHandle>()
    every {savedStateHandle.set(MyViewModel.KEY, "Something") } returns Unit
    val viewModel = MyViewModel(savedStateHandle)
    verify { savedStateHandle.set(MyViewModel.KEY, "Something") }
}