Функция setUP () выдает исключение NullPointerException при использовании @BeforeEach в Junit, - PullRequest
0 голосов
/ 09 мая 2020

Я новичок в Junit и Mockito. Итак, я использовал Mockito и наткнулся на Null PointerException, которое было выброшено из-за @InjectMocks, поэтому наткнулся на статью, в которой показано, как избавиться от @InjectMocks с помощью

    SomeBusinessImpl businessImpl;
    @BeforeEach
    void setUP() {
        final int numberOfElements = 10;
        int[] createdData = (new CreateData()).getCreatedData(numberOfElements);
        when(dataServiceMock.retreiveAllData()).thenReturn(createdData);
        businessImpl = new SomeBusinessImpl(dataServiceMock); 
    }

, но это не сработало. Он снова выбрасывал исключение NullPointerException в третьей строке, когда (dataServiceMock.retreiveAllData ()). ThenReturn (createdData);

My stackTrace

    java.lang.NullPointerException
    at com.floatanddouble.mockitodemo.SomeBusinessImplMockAnnotationsTest.setUP(SomeBusinessImplMockAnnotationsTest.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptLifecycleMethod(TimeoutExtension.java:111)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptBeforeEachMethod(TimeoutExtension.java:67)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeMethodInExtensionContext(ClassBasedTestDescriptor.java:464)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$synthesizeBeforeEachMethodAdapter$16(ClassBasedTestDescriptor.java:449)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachMethods$2(TestMethodTestDescriptor.java:159)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:187)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:187)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachMethods(TestMethodTestDescriptor.java:156)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

И так как это не работает. У меня много избыточного кода в моем классе SomeBusinessImplMockAnnotationsTest

    package com.floatanddouble.mockitodemo;

    import static org.junit.jupiter.api.Assertions.assertEquals;
    import static org.mockito.Mockito.mock;
    import static org.mockito.Mockito.when;

    import org.junit.jupiter.api.BeforeAll;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.mockito.Mock;

    class SomeBusinessImplMockAnnotationsTest {

        @Mock
        DataService dataServiceMock;

    //  @InjectMocks - Does not inform of the failure, and NullPointerException is thrown cause InjectMocks can
    //  can only inject mocks using setter injection, or constructor injection.
    //  SomeBusinessImpl businessImpl;
    //  @BeforeEach
    //  void setUP() {
    //      final int numberOfElements = 10;
    //      int[] createdData = (new CreateData()).getCreatedData(numberOfElements);
    //      when(dataServiceMock.retreiveAllData()).thenReturn(createdData);
    //      businessImpl = new SomeBusinessImpl(dataServiceMock); 
    //  }

        @Test
        void testFndTheGreatestFromAllData() {
            final int numberOfElements = 10;
            int[] createdData = (new CreateData()).getCreatedData(numberOfElements);
            DataService dataServiceMock =  mock(DataService.class);
            when(dataServiceMock.retreiveAllData()).thenReturn(createdData);
            SomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);
            int expectedResult = businessImpl.findTheGreatestFromAllData();
            when(businessImpl.getData()).thenReturn(createdData);
            int actualResult = (new GetActualResult()).getActualResult(businessImpl.getData());
            assertEquals(expectedResult , actualResult);
        }

        @Test
        void testFndTheGreatestFromAllDataTwoElement() {
            final int numberOfElements = 2;
            int[] createdData = (new CreateData()).getCreatedData(numberOfElements);
            DataService dataServiceMock =  mock(DataService.class);
            when(dataServiceMock.retreiveAllData()).thenReturn(createdData);
            SomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);
            int expectedResult = businessImpl.findTheGreatestFromAllData();
            when(businessImpl.getData()).thenReturn(createdData);
            int actualResult = (new GetActualResult()).getActualResult(businessImpl.getData());
            assertEquals(expectedResult , actualResult);
        }

        @Test
        void testFndTheGreatestFromAllDataForSingleElement() {
            final int numberOfElements = 1;
            int[] createdData = (new CreateData()).getCreatedData(numberOfElements);
            DataService dataServiceMock =  mock(DataService.class);
            when(dataServiceMock.retreiveAllData()).thenReturn(createdData);
            SomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);
            int expectedResult = businessImpl.findTheGreatestFromAllData();
            when(businessImpl.getData()).thenReturn(createdData);
            int actualResult = (new GetActualResult()).getActualResult(businessImpl.getData());
            assertEquals(expectedResult , actualResult);
        }

    }

    class GetActualResult{

        public int getActualResult(int[] data) {
            int actualResult = Integer.MIN_VALUE;
            for(int element : data)
                actualResult = Math.max(actualResult, element);
            return actualResult;
        }
    }

    class CreateData{

        public int[] getCreatedData(int numberOfElements) {
            int[] createdData = new int[numberOfElements];
            for(int i = 0; i < numberOfElements; i++) {
                createdData[i] = (int)(Math.random()*100);
            }
            return createdData;
        }   
    }

Класс SomeBusinessImpl

    package com.floatanddouble.mockitodemo;

    public class SomeBusinessImpl {
        private DataService dataService;
        private int[] data;

        public SomeBusinessImpl(DataService dataService) {
            this.dataService = dataService;
            data = this.dataService.retreiveAllData();
        }


        public int[] getData() {
            return data;
        }


        int findTheGreatestFromAllData() {  
            int greatest = Integer.MIN_VALUE;

            for(int i : data) {
                if(i > greatest)
                    greatest = i;
            }

            return greatest;
        }
    }

    interface DataService{
        int[] retreiveAllData();
    }

Plase help. Заранее спасибо.

1 Ответ

1 голос
/ 09 мая 2020

Вы должны аннотировать тестовый класс с помощью @ExtendWith(MockitoExtension.class), чтобы инициализировать dataServiceMock
Вот пример тестового кода, который сработал для меня:

package demo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class DemoTest {

    @Mock
    private DemoService demoService;

    @BeforeEach
    public void setUp() {
        Mockito.when(demoService.foo()).thenReturn("mock");
    }

    @Test
    public void test() {
        Assertions.assertEquals("mock", demoService.foo());
    }

    public static class DemoService {
        public String foo() {
            return "bar";
        }
    }

}
...