java.lang.NullPointerException происходит из-за того, что свойство не загружается в Mockito при насмешке метода - PullRequest
0 голосов
/ 29 декабря 2018

Я новичок в Mockito, и у меня возникла проблема из-за того, что свойство не загружается из файла appication.propertie.

Постановка проблемы: я пытаюсь смоделировать метод, который использует свойство изфайл application.properties.Когда элемент управления прибывает в строку для загрузки значения свойства, он показывает нулевое значение, и из-за этого mockito выдает java.lang.NullPointerException.

. Что я ищу, так это как загрузить свойство из файла application.properties при издевании над методом,Здесь я пытаюсь загрузить глобальную переменную partsListGlobal. Пожалуйста, помогите мне, как этого добиться .?

Вот мой фрагмент кода ниже.

@Service
public class ClimoDiagnosticReportServImpl implements ClimoDiagnosticReportService {

    @Value("${PARTS_LIST}")
    private String partsListGlobal;

    @Override
    public boolean getSomeResult() {
        String[] partsListLocal = getPartsList();

        List<String> partsList = Arrays.asList(partsListGlobal);

        if (partsList.contains("PART_X1"))
            return true;
        else
            return false;
    }

    public String[] getPartsList() {
        return partsListGlobal.split(",");// Here is the error occuring due to partsListGlobal is not loading the value from application.properties file.
    }
}

@RunWith(MockitoJUnitRunner.class)
public class ClimoDiagnosticReportServImplTest {

    @InjectMocks
    private ClimoDiagnosticReportServImpl serviceReference1;

    @Mock
    private ClimoDiagnosticReportServImpl serviceReference12;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void getSomeResultTest() {

        boolean result1 = false;
        String[] strArray = new String[2];
        strArray[0] = "P1";
        strArray[1] = "P2";
        Mockito.when(serviceReference12.getPartsList()).thenReturn(strArray);
        boolean result2 = serviceReference1.getSomeResult();
        Assert.assertEquals(result1,result2);

    }
}

Ошибка:

java.lang.NullPointerException на com.test.serviceimpl.ClimoDiagnosticReportServImpl.getPartsList (ClimoDiagnosticReportServImpl.java:68) на com.test.serviceimpl.ClimoDiagnosticRempesiaClimoDiagnosticReportServImplTest.getSomeResultTest (ClimoDiagnosticReportServImplTest.java:74) в sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) в java.lang.reflect.Method.invoke (Method.java:498) в org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall (FrameworkMethod.java:50) в org.junit.internal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:12) вorg.junit.runners.model.FrameworkMethod.invokeExplosively (FrameworkMethod.java:47) в org.junit.internal.runners.statements.InvokeMethod.evaluate (InvokeMethod.java:17) в org.juntein.internRunBefores.evaluate (RunBefores.java:26) в org.junit.runners.ParentRunner.runLeaf (ParentRunner.java:325) в org.junit.runners.BlockJUnit4ClassRunner.runChild (BlockJUnit4Cunjit.itunit.itunit.itunit.itun.itun.itun.itun)..BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:57) в org.junit.runners.ParentRunner $ 3.run (ParentRunner.java:290) в org.junit.runners.ParentRunner $ 1.schedule или родительjunit.runners.ParentRunner.runChildren (ParentRunner.java:288) в org.junit.runners.ParentRunner.access $ 000 (ParentRunner.java:58) в org.junit.runners.ParentRunner $ 2.evaluate (ParentRunner )jв org.junit.runners.ParentRunner.run (ParentRunner.java:363) в org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run (JUnit45AndHigherRunnerImpl.java:37) в org.mont.MockitoJUnitRunner.run (MockitoJUnitRunner.java:62) в org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run (JUnit4TestReference.java:86) в org.eclipse.junun.in(TestExecution.java:38) по адресу org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (RemoteTestRunner.java:459) по адресу org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.RemoteTestRunner.RemoteTestRunner.Re: 678) в org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run (RemoteTestRunner.java:382) в org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (RemoteTestRunner)

Спасибо всем заранее.

1 Ответ

0 голосов
/ 29 декабря 2018

У вас нет никакой зависимости, чтобы издеваться над сервисом.Таким образом, Mockito совершенно не нужен.Вам нужно установить приватное поле String, которое заполняется Spring в вашем приложении с помощью отражения.

Просто следуйте рекомендациям, используя инъекцию cnstructor вместо инъекции в поле, и это сделает ваш код тестируемым (это одна из причин, почему это лучший метод):

@Service 
public class ClimoDiagnosticReportServImpl implements ClimoDiagnosticReportService {

    private String partsListGlobal;

    public ClimoDiagnosticReportServImpl(@Value("${PARTS_LIST}") String partsListGlobal) {
        this.partsListGlobal = partsListGlobal;
    }

    // ...
}

Ваштест теперь можно уменьшить до

public class ClimoDiagnosticReportServImplTest {

    @Test
    public void shouldReturnTrueIfPropertyContainsPartX1() {
        ClimoDiagnosticReportServImpl service = new ClimoDiagnosticReportServImpl("a,b,c,PART_X1,d");
        assertTrue(service.getSomeResult());
    }

    @Test
    public void shouldReturnFalseIfPropertyDoesNotContainPartX1() {
        ClimoDiagnosticReportServImpl service = new ClimoDiagnosticReportServImpl("a,b,c,d");
        assertFalse(service.getSomeResult());
    }
}
...