ObjectBox ToOne 对象仅在 Android 本地单元测试时在实体内部为空

ObjectBox ToOne object is null inside entity only on Android Local Unit Testing

我正在尝试为我的一个存储库编写测试,但由于以下错误,我无法保存我的实体对象:

java.lang.IllegalStateException: ToOne object is null inside br.com.CalendarEvent

我的实体是这两个:

@Entity
data class CalendarEvent(
    @Id var boxId: Long = 0,

    @Index var id: String = UUID.randomUUID().toString(),

    var userId: String = "",

    var title: String = "",

    var discipline: String = "",

    var hour: Int = 1,

    var dateInEpochDay: Long = 0L,

    var isOnline: Boolean = false,

    var estimatedTime: Int = 1,

    var userAttended: Boolean? = null) {

    lateinit var nucleus: ToOne<SupportNucleus>

    lateinit var specialNeeds: ToMany<SpecialNeed>

}
@Entity
data class SupportNucleus(
@Id var boxId: Long = 0,

@Index var id: String = UUID.randomUUID().toString(),

var name: String = "",

var location: String = "",

var contact: String = "",

var phones: String = "",

var startWorkingHour: Int = 9,

var endWorkingHour: Int = 23,

@Transient var unavailableDays: List<Long> = listOf())

如您所见,这两个实体都有它们的无参数构造函数,当我保存 CalendarEvent 运行 应用程序或 运行 仪器测试时,我工作得很好。此错误仅发生在本地单元测试

我的测试class:

class CalendarBoxRepositoryTest : BaseObjectBoxTest() {

    lateinit var subjectRepository: CalendarRepository

    var dataSourceMock: CalendarDataSource = mockk()
    var dataMapperMock: CalendarDataMapper = mockk()

    @Before
    fun setup() {
        subjectRepository = CalendarBox(dataSourceMock)
    }


    @Test
    fun save_calendar_event_correctly() {
        //Given no event was saved
        val calendarBoxBefore = store?.boxFor(CalendarEvent::class.java)
        assertEquals(0, calendarBoxBefore?.all?.size)

        val calendar = CalendarEvent(userId = "userId", title = "Title", discipline = "Discipline",
            dateInEpochDay = 123, isOnline = false, estimatedTime = 1, userAttended = null)

        val nucleus = SupportNucleus(name = "Support")


        calendar.nucleus = ToOne(calendar, CalendarEvent_.nucleus)
        calendar.nucleus.target = nucleus

        //When Saved
        runBlocking {
            subjectRepository.saveCalendarEvent(calendar)
        }

        //Verify saved correctly
        val calendarBoxAfter = store?.boxFor(CalendarEvent::class.java)
        assertEquals(1, calendarBoxAfter?.all?.size)
    }
}

当我在保存后尝试获取以断言它已正确保存顺便说一句时,实际上发生了错误。

尝试从 ToOne 中删除 lateinit 并立即初始化它:

@Entity
data class CalendarEvent(
...
    ) {

    var nucleus = ToOne<SupportNucleus>(this, CalendarEvent_.nucleus)

}

注意:Android 项目不再需要 ToOne/ToMany 初始化,因为 ObjectBox 1.5 或更新版本 运行 从 Android Studio 测试或直接 运行 Gradle 任务,例如testDebugUnitTest.

检查是否像 objectboxTransformDebugUnitTest 这样的 Gradle 任务在测试任务(默认设置)之前运行。