gpt4 book ai didi

java - 编写 JUnit 测试以检查 SharedPreferences 数据

转载 作者:太空狗 更新时间:2023-10-29 16:27:33 25 4
gpt4 key购买 nike

我是 Android 单元测试的新手,我的尝试是 assertTrue 数据已成功传递给方法并保存在 SharedPreferences 中。到目前为止,这是我的测试:

public class AuthTest {

Authorization authorization = new Authorization();

@Before
public void init() {
MockitoAnnotations.initMocks(this);
}

@Test
public void test_IfAuthIsSaved() {
//test if the auth object is saved in the auth object is saved as a..
//..json string in Shared preferences
Auth auth = mock(Auth.class);
authorization.saveAuth(auth);

//test if the auth is received and saved to sharedpreferences
}

}

saveAuth 方法:

public void saveAuth(Auth auth) {
editor.putString("USER_AUTH", new Gson().toJson(auth));
editor.commit();
}

这个断言会是什么样子?

最佳答案

您正在模拟 Auth,它不会与您的代码中的任何内容交互,因此您不能对其进行任何断言。

你需要改变你的测试方法:

第一种方法

  • 模拟 SharedPreferences.Editor 并将其注入(inject)到 Authorization 中。
  • 实例化一个新的 Auth 对象并调用 authorization.saveAuth(auth)
  • 断言 editorMock.putString() 是用预期的 json 调用的。
  • 断言 editorMock.commit() 被调用。

这种方法有一些缺点:

  • 您的测试与实现相结合。
  • 如果您决定以某种其他形式存储 Auth 数据,则需要更改测试
  • 你并不是真的在测试行为(你真正想做的)

第二种方法

  • 创建 SharedPreferences.Editor 的伪实现并将其注入(inject)到 Authorization 中。
  • 创建一个新的 Auth 对象并调用 authorization.saveAuth(auth)
  • 通过调用 authorization.getAuth() 在保存后检索 auth,并断言它与您保存的 Auth 相同。

缺点:* 你需要创建一个 ``SharedPrefereces.Editor``` 的伪实现,用于模拟相同行为的测试目的

优点:* 您的测试未与实现耦合* 您可以在不更改测试的情况下自由更改实现* 你在测试行为而不是方法

备份第二种方法的一些引用:

Now, from a technical point of view, retrieval of a stored object is really a subset of creation, since ...

Domain Driven Design by Eric Evans

关于java - 编写 JUnit 测试以检查 SharedPreferences 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46485606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com