Così ho iniziato a scrivere test per il nostro progetto Java-Spring.Mockito - NullpointerException when stubbing Metodo
Quello che uso è JUnit e Mockito. Si dice che quando uso l'opzione when() ... thenReturn() posso simulare servizi, senza simularli o altro. Quindi quello che voglio fare è, per impostare:
when(classIwantToTest.object.get().methodWhichReturnsAList(input))thenReturn(ListcreatedInsideTheTestClass)
Ma non importa che quando clausola che faccio, ho sempre ottenere un NullPointerException, che ovviamente ha un senso, perché in ingresso è nullo.
anche quando cerco di prendere in giro un altro metodo da un oggetto:
when(object.method()).thenReturn(true)
Lì ho anche ottenere un Nullpointer, perché il metodo ha bisogno di una variabile, che non è impostato.
Ma voglio usare when() .. thenReturn() per aggirare la creazione di questa variabile e così via. Voglio solo assicurarmi che, se una classe chiama questo metodo, non importa cosa, restituisce true o la lista sopra.
È un malinteso fondamentalmente da parte mia, o c'è qualcos'altro che non va?
Codice:
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();
}
}
Ed ecco la mia classe di test:
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);
}
l'oggetto in quando() deve essere un mock creato da Mockito.mock(), non funziona per oggetti reali creati manualmente - non è sicuro se questo è il tuo problema, dal momento che non riesco a capire dove si trova il tuo problema. .. – Nadir
Si prega di inviare un po 'di codice. –
Sembra che 'classIwantToTest.object.get()' result non è un mock, o che 'get()' sta restituendo null. Ma per favore pubblica il tuo codice, mostra il tuo test e inizializza i tuoi mock. – vikingsteve