进行单元测试时无法将值设置为MutableLiveData-抛出java.lang.reflect.InvocationTargetException

问题描述 投票:1回答:1

我有一个具有构建器的User类,并且该类的构造函数是私有的。

public class User {

    private String name;

    private User() {
    }

    public static class UserBuilder {
        private User user;

        public UserBuilder() {
            user = new User();
        }

        public UserBuilder withName(String name) {
            user.name = name;
            return this;
        }

        public User build() {
            return user;
        }
    }
}

然后我想有一个ViewModel类,在这里我想从我的活动/片段中观察到MutableLiveData类的User

public class UserViewModel extends ViewModel {

    private User.UserBuilder userBuilder;
    private MutableLiveData<User> user;

    public UserViewModel() {
        userBuilder = new User.UserBuilder();
        user = new MutableLiveData<>(userBuilder.build());
    }

    public void setName(String name) {
        userBuilder.withName(name);
        user.setValue(userBuilder.build());
    }

    public MutableLiveData<User> getUser() {
        user.setValue(userBuilder.build());
        return user;
    }
}

[在上面的实现中,我发现在从单元测试中调用NullPointerException函数时,它抛出InvocationTargetExceptionsetValue

我搜索了原因,看起来,User类需要具有public构造函数才能与MutableLiveData一起使用。但是,事实并非如此,我尝试制作一个public构造函数,但仍然失败。

我正在尝试编写一些单元测试,并且在logcat中收到以下错误。请注意,我正在使用以下内容来解决我认为的mainThread错误。

@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();

这是我要在单元测试中尝试做的。

@RunWith(MockitoJUnitRunner.class)
public class UserViewModelTest {

    private UserViewModel userViewModel;

    @Mock
    private Observer<User> userObserver;

    @Rule
    public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();

    @Before
    public void setup() {
        initMocks(this);
        userViewModel = new userViewModel();
        userViewModel.getUser().observeForever(userObserver);
    }
}

并且例外是在以下行中。

user.setValue(userBuilder.build());

这里是logcat。

java.lang.NullPointerException
    at androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77)
    at androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116)
    at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:460)
    at androidx.lifecycle.LiveData.setValue(LiveData.java:304)
    at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
    at com.example.viewmodel.UserViewModel.getUser(UserViewModel.java:79)
    at com.example.viewmodels.UserViewModelTest.setup(UserViewModelTest.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:74)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

谢谢!

java android unit-testing android-livedata android-viewmodel
1个回答
0
投票

最后,我可以理解导致异常的原因。看起来当Observer设置为ViewModel时需要花一些时间进行初始化,与此同时,如果我们尝试将setValue设置为LiveData,则会将NullPointerException抛出为[C0 ]尚未初始化。这是@CommonsWare在该问题前面的评论中建议的测试环境设置问题。我非常感谢,因为它使我找到了摆脱异常的方法。

我决定用Kotlin编写单元测试,因为有了ViewModel变量会更容易。我发现一个很好的lateinit。我将在此处发布与测试tutorial here相关的代码。

首先创建一个名为ViewModel的帮助程序类。

MockUtils.kt

最后,测试类应如下所示。

import org.mockito.Mockito

/**
 * Helper function to mock classes with types (generics)
 */
inline fun <reified T> mock(): T = Mockito.mock(T::class.java)

为了摆脱异常,我不得不解决另一个问题。我认为如果在这里提到,对其他开发人员会有所帮助。

我错误地使用了class UserViewModelTest { @get:Rule val rule = InstantTaskExecutorRule() private lateinit var viewModel: UserViewModel private val observer: Observer<User> = mock() @Before fun before() { viewModel = UserViewModel() viewModel.user.observeForever(observer) } @Test fun testUserViewModel() { val expectedUser = viewModel.user.value viewModel.setName("John") val captor = ArgumentCaptor.forClass(User::class.java) captor.run { verify(observer, times(2)).onChanged(capture()) assertNotNull(expectedUser) assertEquals("John", value.name) } } } InstantTaskExecutorRule的不同版本。您可以检查LiveData。我有同样的问题。 tweet from Jeroen Mols here是从LiveData包中导入的,而androidx是使用InstantTaskExecutorRule包导入的-必须按以下说明进行修复。

android

我用这个问题的简单类创建了一个implementation "androidx.lifecycle:lifecycle-viewmodel:2.1.0" implementation "androidx.lifecycle:lifecycle-livedata:2.1.0" implementation "androidx.lifecycle:lifecycle-extensions:2.1.0" testImplementation "androidx.arch.core:core-testing:2.1.0" ,因此任何人都可以使用自己的开发环境来检查和运行单元测试。编码愉快!

© www.soinside.com 2019 - 2024. All rights reserved.