Я пытаюсь выполнить тестирование тестового приложения springboot, которое я унаследовал.org.mockito.Mockito.mock не эффективен, даже если аргументы верны
Вот как я инициализацию насмешливое часть испытания прибора:
public class ValidationServiceTest {
private Logger LOG = null;
private final Long INVALID_ID = -1L;
private Long custId = 4;
private String username = "foo";
cRepository repo;
Customer customer = null;
ValidationService = null;
@Before
public void setUp() {
validationService = new ValidationService();
customer = new Customer();
customer.setUsername(username);
customer.setCustId(custId);
repo = mock(cRepository.class);
when(repo.searchByUsername(any(String.class))).thenReturn(customer);
MockitoAnnotations.initMocks(this);
}
@Test
public void getCustIdTest() {
Long result = .getCustId(username);
}
}
Тогда в производственной части, у меня есть эта строка кода:
public Long getCustId(String username) {
// Here it breaks
Customer customer = repo.searchByUsername(username);
return customer.getCustId;
}
Я знаю, что правильные значения (имя пользователя, пароль, идентификатор) передается в код, проверяя журналы. Проблема в том, что строка выше возвращает исключение NullPointerException.
Это что-то явно не так? Я ожидаю, что он вернет клиента с именем пользователя «foo», но это не так.
Стек след за исключением
java.lang.NullPointerException в com.mypkg.db.ValidationService.getCustId (ValidationService.java:27) в com.mypkg.db.ValidationServiceTest.getCustIdTest (ValidationServiceTest.java:77) на sun.reflect.NativeMethodAccessorImpl.invoke0 (нативный метод) на 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.junit.internal.runners.statements.RunBefores.evaluate (RunBefores.java:26) на org.junit.runners.ParentRunner.runLeaf (ParentRunner.java:325) на org.junit.runners.BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:78) в org.junit.runners .BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner $ 3.run (Par entRunner.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.оценить (ParentRunner.java:268) на org.junit.runners.ParentRunner.run (ParentRunner.java:363) на org.junit.runner.JUnitCore.run (JUnitCore.java:137) в com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs (JUnit4IdeaTestRunner.java:119) в com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs (JUnit4IdeaTestRunner.java : 42) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart (JUnitStarter.java:234) на com.intellij.rt.execution.junit.JUnitStarter.main (JUnitStarter.java:74) в sun.reflect.NativeMethodAccessorImpl.invoke0 (нативный метод) в 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 com.intellij.rt.execution.application.AppMain.main (AppMain.Java: 144)
Вы издеваетесь над правильным методом? Вы издеваетесь над методом 'searchByUsername', но вместо этого вызываете метод' findByUsername'. –
Кроме того, только потому, что вы создаете макетный экземпляр 'cRepository' (который не соблюдает соглашения об именах Java и является ужасно неясным именем, BTW), не означает, что производственный код использует этот макет. Опубликуйте весь соответствующий код. –
@ LukeWoodward, спасибо за упоминание ... Я исправил опечатку. –