在对使用 ObjectBox 数据库的类进行单元测试时,我收到此错误:
io.objectbox.exception.DbDetachedException:无法解析分离实体的关系
我已将所有必要的数据实现到我的实体类中,以便在 macOS 上进行单元测试。因此,具有指向自身的一对一和一对多关系的实体关系。
@Entity
data class Category(
@Id var id: Long? = 0,
var title: String?,
@JvmField var parent: ToOne<Category>? = null,
@JvmField @Backlink(to = "parent") var subCategories: ToMany<Category>? = null){
constructor(): this(id = 0, title = "", parent = null, subCategories = null)
constructor(title: String): this(id = 0, title = title, parent = null, subCategories = null)
// normally transformer would add field, but need to manually for local unit tests
@JvmField @Transient var __boxStore: BoxStore? = null
init{
if(parent == null) parent = ToOne(this, Category_.parent)
if(subCategories == null) subCategories = ToMany(this, Category_.subCategories)
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试非常简单:
public class CategoryModelDataMapperTest {
private CategoryModelDataMapper categoryModelDataMapper = new CategoryModelDataMapper();
@Before
public void setUp() throws Exception {
categoryModelDataMapper = new CategoryModelDataMapper();
}
@Test
public void testShouldTransformDomainModelWithoutParentToEntityCorrectly() throws Exception{
final Category category = new Category(10L, "Bar", null, null);
final CategoryModel categoryModel = categoryModelDataMapper.transform(category);
assertEquals((Long) 10L, categoryModel.getId());
assertEquals("Bar", categoryModel.getTitle());
assertNull(categoryModel.getParent());
assertNotNull(categoryModel.getSubCategories());
assertTrue(categoryModel.getSubCategories().isEmpty());
}
}
Run Code Online (Sandbox Code Playgroud)
我正在测试的实际类是法线映射器:
class CategoryModelDataMapper: BaseMapper<Category, CategoryModel>{
override fun transform(from: Category): CategoryModel {
val toModel = CategoryModel()
toModel.id = from.id
toModel.title = from.title
toModel.parent = from.parent?.target?.let { transform(it) }
from.subCategories?.let {
it.forEach{ toModel.subCategories?.add( transform(it)) }
}
return toModel
}
override fun transform(fromList: MutableList<Category>): MutableList<CategoryModel> {
val toList = ArrayList<CategoryModel>(fromList.size)
return fromList.mapTo(toList) { transform(it) }
}
}
Run Code Online (Sandbox Code Playgroud)
我还有一些其他测试正在更详细地测试parent和subCategories,但我在所有测试中都遇到了相同的错误。之前一切正常,但后来出了问题。
小智 5
您有完整的堆栈跟踪吗?否则很难查明问题所在。
我假设异常源自此处(?):
from.subCategories?.let {
it.forEach{ toModel.subCategories?.add( transform(it)) }
}
Run Code Online (Sandbox Code Playgroud)
该 CategoryModel 也是一个带有@Id(assignable=true)?的实体。
toModel.id = from.id
Run Code Online (Sandbox Code Playgroud)
在这种情况下,请确保box.attach(toModel)在修改之前调用ToMany:
CategoryModel toModel = CategoryModel()
toModel.id = from.id
box.attach(toModel) // need to attach box first
toModel.subCategories.add(...)
Run Code Online (Sandbox Code Playgroud)
来源:请参阅ObjectBox 关系文档中的更新 ToMany 部分。
| 归档时间: |
|
| 查看次数: |
851 次 |
| 最近记录: |