I am developing a spring boot app. The service method uploads a PDF into a mongodb repo using GridFsTemplate which is autowired in the service. This service method works via postman client. When I try running a unit test calling the same service method the GridFsTemplate is not initialised and so the the org.springframework.data.mongodb.gridfs.GridFsTemplate.store(...) throws a null pointer. Any assistance are welcomed.
Below is my service implementation:
@Service
public final class UploadServiceImpl implements UploadService {
@Autowired
private SequenceRepository sequenceDao;
@Autowired (required = true)
private GridFsTemplate gridFsTemplate;
@Override
public Long uploadFile(Invoice uploadedInvoice) {
ByteArrayInputStream byteArrayInputStream = null;
if (checkContentType(invoiceInfo.getContentType())) {
invoiceInfo.setPaymentID(sequenceDao.getNextSequenceId(INVOICE_UPLOAD_SEQ_KEY));
byteArrayInputStream = new ByteArrayInputStream(uploadedInvoice.getFileContent());
//Error thrown is java.lang.NullPointerException: null, where gridFsTemplate is null and basically autowire does not work when test is run. GridFSFile gridFSUploadedFile= gridFsTemplate.store(byteArrayInputStream, invoiceInfo.getFileName(), invoiceInfo.getContentType(), invoiceInfo); return 1l;
} else {
return 2l;
}
}
### Below is my Unit Test class for the service
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration
public class UploadServiceTest {
@Mock
private SequenceRepository sequenceRepositoryMock;
//@Autowired
//private Mongo embeddedMongo;
@Autowired
private GridFsTemplate gridFsTemplateMock;
@Mock
private Invoice invoiceMock;
@InjectMocks
private static UploadService uploadService = new UploadServiceImpl();
DBObject fileMetaData = null;
DB db = null;
Jongo jongo = null;
@Before
public void setUp() throws Exception {
db = new Fongo("Test").getDB("Database");
jongo = new Jongo(db);
}
@Test
public void testUploadFile() {
//test 1
Long mockPaymentNo = new Long(1);
Mockito.when(sequenceRepositoryMock.getNextSequenceId(INVOICE_SEQUENCE)).thenReturn(mockPaymentNo);
assertEquals(mockPaymentNo, (Long) sequenceRepositoryMock.getNextSequenceId(INVOICE_SEQUENCE));
//test 2
Invoice dummyInvoice = getDummyInvoice();
InvoiceInfo dummyInvoiceInfo = dummyInvoice.getInvoiceInfo();
MongoCollection invoicesCollection = jongo.getCollection("invoices");
assertNotNull(invoicesCollection.save(dummyInvoiceInfo));
assertEquals(1, invoicesCollection.save(dummyInvoiceInfo).getN());
//Verify that payment ID returned is not null
System.out.println("TEST 2 >>>>>>>>>>>>>>>>>> "+ uploadService);
//test 3 : The following line is the cause of the exception, the service method is called but the GridFsTemplate is not initialized when the test is run. But it works when the endpoint is invoked via postman
uploadService.uploadFile(dummyInvoice);
System.out.println("TEST 3 >>>>>>>>>>>>>>>>>> ");
}
}
Aucun commentaire:
Enregistrer un commentaire