简体   繁体   English

单元测试中的依赖服务空引用异常

[英]Dependency service Null Reference exception in unit testing

I am trying to include Unit testing to my Xamarin PCL project.我正在尝试将单元测试包含到我的 Xamarin PCL 项目中。

This is what I am basically doing :这就是我基本上在做什么:

Login Page class :登录页面类:

 public bool isUserRemembered()
    {
        return DependencyService.Get<IUserDefaults>().getUserRemembered();
    }

    public void setRememberUser(bool check)
    {
        DependencyService.Get<IUserDefaults>().setUserRemembered(check);
    }

UnitTest class (iOS) : UnitTest 类(iOS):

    [Test]
    public void RememberKeyTrueTest()
    {
        LoginPage page = new LoginPage();
        bool isRemember = true;

        page.setRememberUser(isRemember);

        bool value = page.isUserRemembered();
        if (value)
            Pass();
        else
            Fail();
    }

I get Null Reference Exception on this line : DependencyService.Get<IUserDefaults>().setUserRemembered(check) .我在这一行得到空引用异常: DependencyService.Get<IUserDefaults>().setUserRemembered(check)

Will dependency service work with unit testing?依赖服务是否适用于单元测试? Or is there any work around it?或者有什么解决方法吗?

When I use Dependency Injection in my code, I use IoC (Inversion Of Control) to handle the creation of the dependencies in my production code, and manually create my dependencies in my unit tests.当我在我的代码中使用依赖注入时,我使用 IoC(控制反转)来处理我的生产代码中依赖项的创建,并在我的单元测试中手动创建我的依赖项。

My main reason for this is that it is explicit.我这样做的主要原因是它是明确的。 Often I'll be using a Mocking framework to create fake instances so I don't want the extra complexity.通常我会使用 Mocking 框架来创建假实例,所以我不想要额外的复杂性。

A suggestion on your code under test, you have swapped a dependency to your class for a dependency on your DependencyService.关于您的测试代码的建议,您已将类的依赖项交换为对 DependencyService 的依赖项。 I'm not saying don't use the DependencyService but you could pass in the dependency to your constructor of the class.我并不是说不要使用 DependencyService,但您可以将依赖项传递给类的构造函数。 Then your test could pass in a fake instance and the production code would use the DependencyService to get you an IUserDefaults and pass it in. That would make your class easier to test.然后您的测试可以传入一个假实例,生产代码将使用 DependencyService 为您获取 IUserDefaults 并将其传入。这将使您的类更易于测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM