Is it correct to write JUnit test case for Repository like this? Also while running it , Iam getting NullPointerException at line Mockito.when...
here is my test class:
#ContextConfiguration(locations = { "classpath*:resources/invoices-context.xml",
"classpath*:resources/invoices-int-schema.xml" })
public class RoomRepositoryTest {
#Autowired
RoomRepository roomRepository;
private RoomEntity roomEntity;
#Test
public void findRommByDateTest() throws ParseException {
String startDate = "27-07-2020";
sDate = new SimpleDateFormat("dd-mm-yyyy").parse(startDate);
String endDate = "28-07-2020";
eDate = new SimpleDateFormat("dd-mm-yyyy").parse(endDate);
String roomType = "SINGLE";
roomEntity = new RoomEntity();
roomEntity.setRoomId(1);
roomEntity.setRoomPrice(6000);
roomEntity.setRoomStatus("AVAILABLE");
roomEntity.setRoomType("SINGLE");
Mockito.when(
roomRepository.findRoomByDate(Mockito.any(Date.class), Mockito.any(Date.class), Mockito.anyString()))
.thenReturn(roomEntity.getRoomId());
int id = roomRepository.findRoomByDate(Mockito.any(Date.class), Mockito.any(Date.class), Mockito.anyString());
assertEquals(1, id);
}
}
Instead of mocking the database fetch function, you can just use the embedded database setup with some annotations. It helps us to test the query efficiently. If you are using an in-memory database(embedded) first you have to add (save) entry in the table. Then your query function should fetch the data. With the help of this you can easily debug the null pointer exceptions.
Eg:
#SpringBootTest
#AutoConfigureTestDatabase
#ContextConfiguration(locations = { "classpath*:resources/invoices-context.xml",
"classpath*:resources/invoices-int-schema.xml" })
public class RoomRepositoryTest {
#Autowired
RoomRepository roomRepository;
private RoomEntity roomEntity;
#Test
public void findRommByDateTest() throws ParseException {
String startDate = "27-07-2020";
sDate = new SimpleDateFormat("dd-mm-yyyy").parse(startDate);
String endDate = "28-07-2020";
eDate = new SimpleDateFormat("dd-mm-yyyy").parse(endDate);
String roomType = "SINGLE";
roomEntity = new RoomEntity();
roomEntity.setRoomId(1);
roomEntity.setRoomPrice(6000);
roomEntity.setRoomStatus("AVAILABLE");
roomEntity.setRoomType("SINGLE");
//adding data for testing
roomRepository.save(roomEntity)
//test the actual function
int id = roomRepository.findRoomByDate(sDate,eDate);
assertEquals(1, id);
}
Related
I am trying to figure out mickito test for Named Jdbc Template but unable to do so. I did googling but did not find any accurate result. Below is example Code.
Student.class
#Data
public class Student {
private int id;
private String name;
private String address;
public Student(ResultSet rs) throws SQLException {
id = rs.getInt("id");
name = rs.getString("name");
address = rs.getString("address");
}
}
Student class takes ResultSet argument in constructor and mapped all column to variable .
StudentService.class
public class StudentService {
#Autowired
#Qualifier("namedJdbcTemplate")
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public Student gerStudent(String id) {
Student student;
String selectStudent = "select id , name ,address from student where id=:id";
MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
mapSqlParameterSource.addValue(id, "id");
student = namedParameterJdbcTemplate.query(selectStudent, mapSqlParameterSource, resultSet -> {
Student response = new Student(resultSet);
return response;
});
return student;
}
}
Can anyone please help on Mockito Test for below line of code?
student = namedParameterJdbcTemplate.query(selectStudent, mapSqlParameterSource, resultSet -> {
Student response = new Student(resultSet);
return response;
});
I'm trying to solve a problem: When user click on delete a record and instead of delete it, this record will change status to 'false'.
I suppose to create stored procedures in MySQL like "getAllUser", "changeStatus" but I'm confusing what I have to do.
This is structure of my project:
-configuration
JpaConfiguration
-controller
RestApiController
-model
User
-Repository
UserRepository
-Service
UserService
UserServiceImpl
Then I expect the index page only get records that have status is 'true'.
Procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `getAllUsers`()
BEGIN
SELECT * FROM APP_USER where status = 0;
END
RestApiController
#RestController
#RequestMapping("/api")
public class RestApiController {
#Autowired
UserService userService;
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public List<User> getAllUsers(Boolean status){
Boolean statusWhere = org.apache.commons.lang3.BooleanUtils.isNotTrue(false);
List<User> users = userServiceImpl.getAllUsers(statusWhere);
if (users == null){
return new ArrayList<>();
} else {
return users;
}
}
// Change status
#RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?>deleteUserById(#PathVariable("id") long id){
logger.info("Delete User with id {}", id);
User currentUser = userService.findById(id);
currentUser.setStatus(true);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}
model/User
#Entity
#NamedStoredProcedureQueries({
#NamedStoredProcedureQuery(
name = "getAllUsers",
procedureName = "getAllUsers",
resultClasses = {User.class},
parameters = {
#StoredProcedureParameter(
mode = ParameterMode.IN,
name = "status",
type = Boolean.class)
}
)
})
service/UserServiceImpl
#Component
#Service("userService")
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
private EntityManager entityManager;
#SuppressWarnings("unchecked")
public List<User> getAllUsers(Boolean status){
StoredProcedureQuery storedProcedureQuery = this.entityManager.createNamedStoredProcedureQuery("getAllUsers");
storedProcedureQuery.setParameter("status",status);
storedProcedureQuery.execute();
return storedProcedureQuery.getResultList();
}
public boolean isUserExist(User user) {
return findByName(user.getName()) != null;
}
}
Junit tests for Spring Boot application.
Does anyone have any suggestions on how I might achieve this using JUnit and Mockito?
#Autowired
JdbcTemplate jdbcTemplate;
public List<Student> getStudentDetails(String department) {
List<Student> results = new LinkedList<String>();
results = jdbcTemplate.query("SELECT * FROM STUDENT WHERE DEPARTMENT = ?", new PreparedStatementSetter() {
#Override
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setString(1, department);
preparedStatement.setFetchSize(10);
}
}, new ResultSetExtractor<List<Student>>() {
#Override
public List<Student> extractData(ResultSet rs) throws SQLException {
List<Student> students = new ArrayList<>();
while (rs.next()) {
Student student = new Student<>();
student.setDepartment(rs.getString("NAME"));
student.setName(rs.getString("DEPARTMENT"));
students.add(student);
}
return students;
}
});
return results
}
Code that you have is related to database and in my opinion it should be tested using some database. Usual practice is to use embedded database ( e.g. h2 ). People do it, since using unit tests it's not possible to check if query really works, since you don't actually run it. So I would combine integration and unit tests for testing of this class.
Unit test would be something like this:
#ExtendWith(MockitoExtension.class)
class StubTest {
#Mock
JdbcTemplate jdbcTemplate;
#InjectMocks
Stub stub;
#Test
void whenExecuteQuery_thenExtractDataCorrectly() throws SQLException {
//GIVEN
ArgumentCaptor<PreparedStatementSetter> setterCaptor = ArgumentCaptor.forClass(PreparedStatementSetter.class);
ArgumentCaptor<ResultSetExtractor> extractorCaptor = ArgumentCaptor.forClass(ResultSetExtractor.class);
//WHEN
stub.getStudentDetails("TEST");
//THEN
verify(jdbcTemplate).query(anyString(), setterCaptor.capture(), extractorCaptor.capture());
//AND
PreparedStatementSetter setter = setterCaptor.getValue();
PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class);
setter.setValues(preparedStatement);
verify(preparedStatement).setString(1, "TEST");
verify(preparedStatement).setFetchSize(10);
verifyNoMoreInteractions(preparedStatement);
//AND
ResultSetExtractor extractor = extractorCaptor.getValue();
ResultSet rs = Mockito.mock(ResultSet.class);
when(rs.next()).thenReturn(true).thenReturn(false);
when(rs.getString(anyString())).thenReturn("TEST","name");
verifyNoMoreInteractions(rs);
List<Student> students = (List<Student>) extractor.extractData(rs);
assertThat(students.get(0).getName()).isEqualTo("name");
assertThat(students.get(0).getDepartment()).isEqualTo("TEST");
}
}
Here I'm just capturing arguments with business logic that we send to query method. Then I run overridden methods of arguments and verify that they work as we expect.
I'm writing the Junit test case for a class which is extended by an abstract class. This base abstract class has an autowired object of a different class which is being used in the class I'm testing.
I'm trying to mock in the subclass, but the mocked object is throwing a NullPointerException.
Example:
// class I am testing
public class GetTransactionsForProcessorGroupActivity extends GetTransactionsBaseActivity {
private static final Logger log = LogManager.getLogger(GetTransactionsForProcessorGroupActivity.class);
public GetTransactionsForProcessorGroupActivity(ARHFactory arhFactory, MetricsFactory metricsFactory) {
super(arhFactory, metricsFactory);
}
#Override
protected List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException {
final String paymentProcessorGroup = HerdDocumentUtils.getPaymentProcessor(herdDocument);
final Date runDate = HerdDocumentUtils.getRunDate(herdDocument);
final List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
List<ProcessorTransactionWindow> processingWindows = new ArrayList<ProcessorTransactionWindow>();
for (final String processor : paymentProcessorList) {
ProcessorTransactionWindow transactionWindow = ProcessorCalendarUtils.getProcessorTransactionWindow(processor, runDate);
processingWindows.add(transactionWindow);
final Date processingFromDate = transactionWindow.getFromDate();
final Date processingToDate = transactionWindow.getToDate();
//NullpointerException on this line, as OverseasTransactionStore mock object returns null.
final List<OverseasTransaction> transactions = overseasTransactionsStore
.queryOverseasTransactionsOnPPTimelineandDates(processor, processingFromDate, processingToDate);
overseasTransactionList.addAll(transactions);
}
HerdDocumentUtils.putProcessingWindowDetails(herdDocument, processingWindows);
return overseasTransactionList;
}
}
// Base class
public abstract class GetTransactionsBaseActivity extends CoralHerdActivity implements ActionRequestHandler {
private static final Logger log = LogManager.getLogger(GetTransactionsBaseActivity.class);
#SuppressWarnings("unchecked")
private static final Map<String, String> S3_CONFIGURATION = AppConfig.findMap(Constants.S3_CONFIGURATION_KEY);
private static final String S3_BUCKET = S3_CONFIGURATION.get(Constants.BUCKET_NAME);
private static final class Status {
private static final String PROCESSOR_DETAILS_NOT_FOUND = "NoPaymentProcessorDetailsPresent";
private static final String TRANSACTIONS_OBTAINED = "TransactionsObtained";
private static final String NO_TRANSACTIONS_TO_BE_CONSIDERED = "NoTransactionsToBeConsidered";
private static final String NEGATIVE_OR_ZERO_AMOUNT = "NegativeOrZeroAmount";
}
protected final ARHFactory arhFactory;
protected final MetricsFactory metricsFactory;
#Autowired
OverseasTransactionsStore overseasTransactionsStore;
#Autowired
S3ClientProvider s3ClientProvider;
protected abstract List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException;
#Override
public ActionResponse postActionRequest(final ActionRequest request) throws Exception {
TimedARH timedARH = (TimedARH) arhFactory.createARH();
timedARH.setHandler(this);
return timedARH.handle(request);
}
public ActionResponse handle(final ActionRequest request) throws Exception {
final Document herdDocument = HerdDocumentUtils.getFundFlowDocument(request);
final Metrics metrics = MetricsLogger.getMetrics(metricsFactory);
final String paymentProcessor = HerdDocumentUtils.getPaymentProcessor(herdDocument);
try {
final List<OverseasTransaction> overseasTransactionList;
MetricsLogger.logFundFlowExecution(metrics, paymentProcessor);
try {
overseasTransactionList = getOverseasTransactions(herdDocument);
} catch (ProcessorConfigurationException e) {
return new ActionComplete(Status.PROCESSOR_DETAILS_NOT_FOUND, herdDocument);
}
if (CollectionUtils.isEmpty(overseasTransactionList)) {
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, 0, BigDecimal.ZERO);
return new ActionComplete(Status.NO_TRANSACTIONS_TO_BE_CONSIDERED, herdDocument);
}
final String s3ObjectKey = getS3ObjectKey(request, paymentProcessor);
storeTransactionsInS3(overseasTransactionList, S3_BUCKET, s3ObjectKey);
final int itemCount = overseasTransactionList.size();
BigDecimal totalAmount = BigDecimal.ZERO;
for (OverseasTransaction overseasTransaction : overseasTransactionList) {
if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_CHARGE)) {
totalAmount = totalAmount.add(overseasTransaction.getOverseasAmount());
} else if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_REFUND)) {
totalAmount = totalAmount.subtract(overseasTransaction.getOverseasAmount());
}
}
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, itemCount, totalAmount);
HerdDocumentUtils.putS3Location(herdDocument, S3_BUCKET, s3ObjectKey);
HerdDocumentUtils.putTotalAmount(herdDocument, totalAmount);
HerdDocumentUtils.putTransactionItemCount(herdDocument, itemCount);
HerdDocumentUtils.putPaymentProcessor(herdDocument, paymentProcessor);
if (totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
log.info("Total amount to disburse is zero or negative. {}", totalAmount);
return new ActionComplete(Status.NEGATIVE_OR_ZERO_AMOUNT, herdDocument);
}
return new ActionComplete(Status.TRANSACTIONS_OBTAINED, herdDocument);
} finally {
MetricsLogger.closeMetrics(metrics);
}
}
}
// Test class
#RunWith(PowerMockRunner.class)
#PowerMockIgnore({ "javax.management.*" })
#PrepareForTest({ HerdDocumentUtils.class, ProcessorGroupLookup.class })
public class GetTransactionsForProcessorGroupActivityTest extends AppConfigInitializedTestBase {
private static HerdInput herdInput;
private static HerdOutput herdOutput;
private static final String paymentProcessorGroup = "BillDesk";
private static final String paymentProcessorGroupNotFound = "IndiaPaymentGateway";
#Mock
ActionRequest request;
#Mock
WorkItemIdentifier workItemId;
#Mock
private CoralHerdActivity coralHerdActivity;
#Mock
Metrics metrics;
#Mock
Map<String, String> S3_CONFIGURATION_MAP;
#Mock
MetricsFactory metricsFactory;
#Mock
ARHFactory arhFactory;
#Mock
Document herdDocument;
#Mock
OverseasTransactionsStore overseasTransactionsStore;
#Mock
S3ClientProvider s3ClientProvider;
// #InjectMocks
// GetTransactionsForProcessorGroupActivity getTransactionsBaseActivityTest;
// new GetTransactionsForProcessorGroupActivity(arhFactory, metricsFactory);
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(HerdDocumentUtils.class);
// PowerMockito.mockStatic(ProcessorGroupLookup.class);
// GetTransactionsBaseActivity getTransactionsBaseActivity = new GetTransactionsBaseActivity(overseasTransactionsStore);
}
#Test
public void testEnact() {
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class, Mockito.CALLS_REAL_METHODS);
Mockito.when(coralHerdActivity.enact(herdInput)).thenReturn(herdOutput);
final HerdOutput actualHerdOutput = getTransactionsForProcessorGroupActivity.enact(herdInput);
Assert.assertNotNull(actualHerdOutput);
}
#Test
public void testgetpaymentProcessorList() throws Exception {
Date date = new Date();
List<String> paymentProcessorList;
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
assertNotNull(paymentProcessorList);
}
#Test(expected = ProcessorConfigurationException.class)
public void testpaymentProcessorListNotFound() {
Date date = new Date();
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument))
.thenReturn(paymentProcessorGroupNotFound);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroupNotFound);
assertNotNull(paymentProcessorList);
}
#Test
public void canGetOverseasTransactiontest() throws Exception {
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class);
// OverseasTransactionsStore overseasTransactionsStore =
// Mockito.mock(OverseasTransactionsStoreImpl.class);
Date date = new Date();
MockitoAnnotations.initMocks(this);
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
// List<String> paymentProcessorList = new ArrayList<>();
// paymentProcessorList.add("BillDesk");
// PowerMockito.when(ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup))
// .thenReturn(paymentProcessorList);
String fromDate = "Sat Mar 16 23:59:59 IST 2019";
String toDate = "Sat Mar 16 23:59:59 IST 2019";
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
List<OverseasTransaction> overseasTransactionList1 = createMockOverseasTransaction();
Mockito.doReturn(overseasTransactionList1).when(overseasTransactionsStore)
.queryOverseasTransactionsOnPPTimelineandDates(Mockito.isA(String.class), Mockito.isA(Date.class),
Mockito.isA(Date.class));
Mockito.when(getTransactionsForProcessorGroupActivity.getOverseasTransactions(herdDocument))
.thenCallRealMethod();
List<OverseasTransaction> overseasTransactionList = getTransactionsForProcessorGroupActivity
.getOverseasTransactions(herdDocument);
assertNotNull(overseasTransactionList);
// assertEquals(overseasTransactionList.getPaymentProcessorID(), actual);
}
private List<OverseasTransaction> createMockOverseasTransaction() {
Date date = new Date();
BigDecimal num = new BigDecimal(100001);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
OverseasTransaction overseasTransaction = new OverseasTransaction();
overseasTransaction.setPurchaseID("purchaseID");
overseasTransaction.setSignatureID("signatureID");
overseasTransaction.setPaymentProcessorTransactionID("paymentProcessorTransactionID");
overseasTransaction.setType("Charge");
overseasTransaction.setSubType("subType");
overseasTransaction.setTransactionTimestamp(date);
overseasTransaction.setPaymentMethod("paymentMethod");
overseasTransaction.setTotalAmount(num);
overseasTransaction.setOverseasAmount(num);
overseasTransaction.setCurrency("currency");
overseasTransaction.setMarketplaceID("marketplaceID");
overseasTransaction.setOrderMetadata("orderMetadata");
overseasTransaction.setDisbursementID("disbursementID");
overseasTransaction.setReconState(1);
overseasTransaction.setPaymentProcessorID("BillDesk");
overseasTransaction.setRemittanceFileStatus("remittanceFileStatus");
overseasTransaction.setCrowID("crowID");
overseasTransaction.setSource("source");
overseasTransactionList.add(overseasTransaction);
return overseasTransactionList;
}
}
In my test file when I mock OverseasTransaction object, it gives me a NullPointerException. Do you have any suggestions about how we can mock this? All the above commented lines in my test indicates the things I tried but they still seem to throw the same error.
StackTrace of error: while executing canGetOverseasTransactiontest
N/A
java.lang.NullPointerException
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivity.getOverseasTransactions(GetTransactionsForProcessorGroupActivity.java:71)
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivityTest.canGetOverseasTransactiontest(GetTransactionsForProcessorGroupActivityTest.java:172)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
You need to create object of Class which for which you are writing the test. i.e. GetTransactionsForProcessorGroupActivity. There is what you can do
#RunWith(MockitoJUnitRunner.class)
public class GetTransactionsForProcessorGroupActivityTest {
#InjectMocks
private GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity;
#Mock
private OverseasTransaction overseastransaction;
#Test
public void test() {
Mockito.when(overseastransaction.somemethod()).thenReturn(something);
}
}
This will make sure that getTransactionsForProcessorGroupActivity is created and overseastransaction is injected with mock object.
Please note the class annotation #RunWith. This make sure that all the properties are injected with mock object properly. Also, you can use Mockito instead of PowerMockito.
You can add a protected setter in the abstract class and then in your GetTransactionsForProcessorGroupActivity you can call the setter in the constructor.
Then you just use #Mock the field you need to set and then you either use #InjectMocks or more suggested to call the constructor in the #Setup method including the mock field to be set.
Hi there im having some issues with MongoDb i have a CRUD and this is the code im using
First the POJO:
#Data
#Document(collection = "Informacion")
public class Informacion {
//Declaration code
public Informacion(Pais pais, Date fechaCreacion, String nombre, Boolean sexo,
Date fechaNacimiento, List<Preferencias> preferencias, String numTelefono, String usuario,
List<RedesSociales> redes, String contraseniaTW, String contraseniaFB, String contraseniaIG,
Grupo grupo, String paqChip, String email, String contraseniaMail, String fuente,
Date fechaRecarga) {
this.pais = pais;
this.fechaCreacion = fechaCreacion;
this.nombre = nombre;
this.sexo = sexo;
this.fechaNacimiento = fechaNacimiento;
this.preferencias = preferencias;
this.numTelefono = numTelefono;
this.usuario = usuario;
this.redes = redes;
this.contraseniaTW = contraseniaTW;
this.contraseniaFB = contraseniaFB;
this.contraseniaIG = contraseniaIG;
this.grupo = grupo;
this.paqChip = paqChip;
this.email = email;
this.contraseniaMail = contraseniaMail;
this.fuente = fuente;
this.fechaRecarga = fechaRecarga;
}
}
Now the DAO:
#Repository
public interface informacionRepo extends MongoRepository<Informacion,String> {
Informacion findByIdInformacion(String id);
}
And the controller:
#RestController
#RequestMapping("/Informacion")
public class InformacionControlador {
#Autowired
private informacionRepo informacioRepo;
public InformacionControlador(informacionRepo informacioRepo) {
this.informacioRepo = informacioRepo;
}
#GetMapping("/Listar")
public List<Informacion> getAll(){
List<Informacion> info = this.informacioRepo.findAll();
System.out.println(info.isEmpty());
return info;
}
#PutMapping
public void insert(#RequestBody Informacion informacion){
this.informacioRepo.insert(informacion);
}
public void update(#RequestBody Informacion informacion){
this.informacioRepo.save(informacion);
}
#DeleteMapping("/Listar/{id}")
public void delete(#PathVariable("id") String id){
this.informacioRepo.deleteById(id);
}
#GetMapping("/Listar/{id}")
public Informacion getById(#PathVariable("id") String id){
Informacion info = this.informacioRepo.findByIdInformacion(id);
return info;
}
}
Im using POSTMAN to test the methods above but im getting empty answers, the data is already set on the Database, im using a method call seeder that fills the data also y check it with robo mongo and the data is there but still getting empty answers also when i try the insert method i get 403 error.
Thanks for your help
This is the answer seen from the web browser
The problem was that im using the annotation #Data from lombok but i didnt enable annotation processing in the IDE just enable it and works :D