Mockito - 存根方法时的NullpointerException [英] Mockito - NullpointerException when stubbing Method

查看:182
本文介绍了Mockito - 存根方法时的NullpointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我开始为Java-Spring项目编写测试。

So I started writing tests for our Java-Spring-project.

我使用的是JUnit和Mockito。据说,当我使用when()... thenReturn()选项时,我可以模拟服务,而不需要模拟它们。所以我想做的是设置:

What I use is JUnit and Mockito. It's said, that when I use the when()...thenReturn() option I can mock services, without simulating them or so. So what I want to do is, to set:

when(classIwantToTest.object.get().methodWhichReturnsAList(input))thenReturn(ListcreatedInsideTheTestClass)  

但无论我做什么时候的子句,我总是得到一个NullpointerException,当然有道理,因为输入是空的。

But no matter which when-clause I do, I always get a NullpointerException, which of course makes sense, because input is null.

当我尝试从对象模拟另一种方法时:

Also when I try to mock another method from an object:

when(object.method()).thenReturn(true)

我还有一个Nullpointer,因为该方法需要一个未设置的变量。

There I also get a Nullpointer, because the method needs a variable, which isn't set.

但我想使用when().. thenReturn()来绕过创建这个变量等等。我只是想确保,如果任何类调用此方法,那么无论如何,只返回true或上面的列表。

But I want to use when()..thenReturn() to get around creating this variable and so on. I just want to make sure, that if any class calls this method, then no matter what, just return true or the list above.

这是我的一个基本误解那边还是有其他问题吗?

Is it a basically misunderstanding from my side, or is there something else wrong?

代码:

public class classIWantToTest implements classIWantToTestFacade{
        @Autowired
        private SomeService myService;

        @Override
        public Optional<OutputData> getInformations(final InputData inputData) {
            final Optional<OutputData> data = myService.getListWithData(inputData);
            if (data.isPresent()) {
                final List<ItemData> allData = data.get().getItemDatas();
                    //do something with the data and allData
                return data;
            }

            return Optional.absent();
        }   
}

这是我的测试类:

public class Test {

    private InputData inputdata;

    private ClassUnderTest classUnderTest;

    final List<ItemData> allData = new ArrayList<ItemData>();

    @Mock
    private DeliveryItemData item1;

    @Mock
    private DeliveryItemData item2;



    @Mock
    private SomeService myService;


    @Before
    public void setUp() throws Exception {
        classUnderTest = new ClassUnderTest();
        myService = mock(myService.class); 
        classUnderTest.setService(myService);
        item1 = mock(DeliveryItemData.class);
        item2 = mock(DeliveryItemData.class);

    }


    @Test
    public void test_sort() {
        createData();
        when(myService.getListWithData(inputdata).get().getItemDatas());

        when(item1.hasSomething()).thenReturn(true);
        when(item2.hasSomething()).thenReturn(false);

    }

    public void createData() {
        item1.setSomeValue("val");
        item2.setSomeOtherValue("test");

        item2.setSomeValue("val");
        item2.setSomeOtherValue("value");

        allData.add(item1);
        allData.add(item2);


}


推荐答案

对于布尔方法,没有存根的方法的默认返回值是 false ,返回集合或映射的方法的空集合或映射以及 null 否则。

The default return value of methods you haven't stubbed yet is false for boolean methods, an empty collection or map for methods returning collections or maps and null otherwise.

当(...)内的方法调用C>。在你的示例中当(myService.getListWithData(inputData).get())将导致NullPointerException,因为 myService.getListWithData(inputData) null - 它之前没有存根。

This also applies to method calls within when(...). In you're example when(myService.getListWithData(inputData).get()) will cause a NullPointerException because myService.getListWithData(inputData) is null - it has not been stubbed before.

一个选项是为所有人创建模拟中间返回值并在使用前将它们存根。例如:

One option is create mocks for all intermediate return values and stub them before use. For example:

ListWithData listWithData = mock(ListWithData.class);
when(listWithData.get()).thenReturn(item1);
when(myService.getListWithData()).thenReturn(listWithData);

或者,您可以在创建模拟时指定不同的默认答案,以使方法返回新的mock而不是null: RETURNS_DEEP_STUBS

Or alternatively, you can specify a different default answer when creating a mock, to make methods return a new mock instead of null: RETURNS_DEEP_STUBS

SomeService myService = mock(SomeService.class, Mockito.RETURNS_DEEP_STUBS);
when(myService.getListWithData().get()).thenReturn(item1);

你应该阅读 Mockito.RETURNS_DEEP_STUBS ,它更详细地解释了这一点,并对其用法提出了一些警告。

You should read the Javadoc of Mockito.RETURNS_DEEP_STUBS which explains this in more detail and also has some warnings about its usage.

我希望这会有所帮助。请注意,您的示例代码似乎有更多问题,例如缺少断言或验证语句以及在模拟上调用setter(这没有任何影响)。

I hope this helps. Just note that your example code seems to have more issues, such as missing assert or verify statements and calling setters on mocks (which does not have any effect).

这篇关于Mockito - 存根方法时的NullpointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆