尝试对使用Realm的项目进行单元测试。我使用领域方法来测试我自己的代码,发现RealmQuery有问题。我想测试是否将对象(1)添加到Realm数据库中; (2)可以取回; (3)如果该对象的set属性符合我的期望。这是我的setup()和Test的一部分。我如何在setup()中存入一个领域数据库(someList是全局的&List )SomeRealmObject some1;some1.setId(1);some1.setName("some1");SomeRealmObject some2;some2.setId(2);some2.setName("some2");someList = new ArrayList<SomeRealmObject>();someList.add(some1);someList.add(some2);我如何在setup()中存根复制到Realm(添加功能)when(mockRealm.copyToRealm).then(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); SomeRealmObject some = (SomeRealmObject) args[0]; userList.add(user); return user; } });我如何在setup()中存根RealmQuery(搜索功能)RealmQuery someRealmQuery = someRealmQuery(); //followed mockito example on githubwhen(mockRealm.where(SomeRealmObject.class)).thenReturn(someRealmQuery);when(realmQuery.equalsTo(anyString, anyInt).thenReturn(someRealmQuery);when(realmQuery.findFirst()).then(findFirstAnswer);问题从这里开始。我需要realmQuery.equalsTo(...)将其参数传递给链中的下一个方法。我认为这是必要的(但我可能错了),因为我应该测试以下两个方法:findFirst()和findAll()。有任何想法吗?我如何在setup()中存根findFirst()Answer findFirstAnswer = new Answer(){ @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); String key = args[0].toString(); //Let's just use an Id search for int id = (int) args[1]; //an example. for(int count = 0; someList.get(count) != null; count++){ if(someList.get(count).getId == id){ return someList.get(count); } return null; //test will fail, someRealmObject not found }}我如何对我的createSomeObject进行单元测试(例如createAccount)@Testpublic void create_someObj_test() { String expectedReturnedName = "someName"; String actualReturnedName; SomeRepositoryImpl manager; //Class with business logic (mvp pattern) SomeRepositoryImpl.initialize(); manager = someRepositoryImpl.getInstance(); SomeRealmObject some = new SomeRealmObject(); some.setID(6); some.setName(expectedReturnedName); //mock adding user to realm, should actually add it to a list mockRealm.beginTransaction(); mockRealm.copyToRealm(some); mockRealm.commitTransaction(); actualReturnedName = mockRealm.where(SomeRealmObject.class).equalTo("id", some.getId()).findFirst().getName().toString(); //PASS if object exists and name matches //FAIL if name does not match //FAIL if nullPointerException because no match/object not found assertEquals(expectedReturnedName, actualReturnedName );} (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 这不是您问题的直接答案。一个直接的答案将是讨论什么是findFirstAnswer及其name属性包含什么。相反,我会问:“您要测试什么”?这不是对Realm数据库库的测试(很好)。在我看来,这几乎就像是对Mockito的测试!如果测试成功,您将知道Mockito Mocks可以返回具有特定名称的对象。通常的做法是将数据层包装在非常薄的API中,例如Spring流行的数据访问对象之类。如果可以模拟数据API,则可以测试业务层中的内容。如果您的数据API需要测试,您还可以测试诸如“此API调用是否转换为正确的查询?”之类的东西。或“如果结果为空,API是否会崩溃?”。对oblique answer感到抱歉,但是我认为,如果您重新考虑要测试的问题,则整个问题可能会消失。 (adsbygoogle = window.adsbygoogle || []).push({});
10-01 12:23