classCastException in Mockito with Java.lang.String - mockito

I have the following piece of code for which I'm writing the unit test using Mockito
if (user != null) {
LDAPCustomer cust = getLDAPCustomer();
LDAPAuthorization auth = getLDAPAuthorization();
cust = getCustomerData( new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.CUSTOMER_MAIL, user));
if (cust != null)
auth = getAuthorizationData(new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.AUTHORIZATION_GUID, cust.getCstAuthGuid()));
if (cust != null && auth!= null && cust.getCstManageeGuids().size() == 1) {
String custGuid = cust.getCstCustGuid();
if (cust.getCstManageeGuids().get(0).equals(custGuid)) {
//No secondary user
try
{
deleteUserAssociations(cust.getCstCustGuid());
resetAuthorization(auth.getCstAuthGuid());
logger.info(cust.getCstCustGuid()+" user successfully perged.");
} catch (Exception e) {
logger.error("Error occured whie try to purging user: "+MiscUtility.getStackTrace(e));
throw new Exception("Error occured whie try to purging user: "+e.getMessage());
}
}
}
}
and here's the mockito code
int size = 1;
//Define the Stub
Mockito.doReturn(mockCustomer).when(ldap).getLDAPCustomer();
Mockito.doReturn(mockAuthorization).when(ldap).getLDAPAuthorization();
Mockito.doReturn(mockCustomer).when(ldap).getCustomerData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.doReturn(mockAuthorization).when(ldap).getAuthorizationData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.when(mockCustomer.getCstManageeGuids().size()).thenReturn(size);
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn("mockCust");
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Mockito.doNothing().when(ldap).deleteUserAssociations(Mockito.anyString());
Mockito.doNothing().when(ldap).resetAuthorization(Mockito.anyString());
I'm getting a ClassCastException as below
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$1ebf8eb1 cannot be cast to java.lang.String
at the line
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Appreciate any help.

Solved it by breaking down the chain.
List<String> lst = new ArrayList<String>();
lst.add("mockVal");
Mockito.when(mockCustomer.getCstManageeGuids()).thenReturn(lst);

Related

Unexpected double WHERE clause in Servicestack OrmLite

We have an issue that occurs at every method call for limited periods of time. Then it works as expected. The issue is that the code produces double WHERE clauses.
We're using Servicestack 4.5.14
The method we have:
protected static void InsertOrUpdate<T>(
IDbConnection connection,
T item,
Expression<Func<T, bool>> singleItemPredicate,
Expression<Func<T, object>> updateOnlyFields = null)
{
var type = item.GetType();
var idProperty = type.GetProperty("Id");
if (idProperty == null)
{
throw new Exception("Cannot insert or update on a class with no ID property");
}
var currentId = (int)idProperty.GetValue(item);
if (currentId != 0)
{
throw new Exception("Cannot insert or update with non-zero ID");
}
var query = connection.From<T>().Where(singleItemPredicate).WithSqlFilter(WithUpdateLock);
T existingItem;
try
{
existingItem = connection.Select(query).SingleOrDefault();
Log.Verbose(connection.GetLastSql);
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
if (existingItem == null)
{
Insert(connection, item);
return;
}
var existingId = (int)idProperty.GetValue(existingItem);
idProperty.SetValue(item, existingId);
try
{
var affectedRowCount = connection.UpdateOnly(item, onlyFields: updateOnlyFields, where: singleItemPredicate);
Log.Verbose(connection.GetLastSql);
if (affectedRowCount != 1)
{
throw new SwToolsException("Update failed");
}
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
}
When it all works, an example output from the logs could be:
SELECT "Id", "Application", "Hostname", "LastContact", "Version", "ToolState", "ServerState"
FROM "ca"."ExecutionHost"
WITH (UPDLOCK) WHERE ("Hostname" = #0)
UPDATE "ca"."ExecutionHost" SET "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE ("Hostname" = #0)
When it fails, the output (same session, only seconds later) was:
SELECT "Id", "Application", "Hostname", "LastContact", "Version", "ToolState", "ServerState"
FROM "ca"."ExecutionHost"
WITH (UPDLOCK) WHERE ("Hostname" = #0)
UPDATE "ca"."ExecutionHost" SET "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE ("Hostname" = #0)
Marked in bold is the addition to the SQL that makes the call to fail. It seems that it adds an additional WHERE clause with the content from the SET clause.
We've been debugging this for a while and don't really know if the issue is on "our" side or in Servicestack.
Any ideas on where to continue?

PowerMockito Error

Need a quick help. I am trying to write a test class and getting below error
"can not resolve the method .thenreturn(org.apache.kafka.clients.producer)
#Test
public void testPublishData_Success() throws java.lang.Exception {
when(GetPropValues.getPropValue(PublisherConstants.ATMID)).thenReturn("ATM");
when(GetPropValues.getPropValue(PublisherConstants.DATA_SOURCE)).thenReturn("PCE");
ReadAndWriteFiles mockFiles = Mockito.mock(ReadAndWriteFiles.class);
PowerMockito.whenNew(ReadAndWriteFiles.class).withNoArguments().thenReturn(mockFiles);
Mockito.when(mockFiles.getAllFiles()).thenReturn("someValue");
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer);
producer.publishData(null, "Test", "Data1");
}
Powermockito is fine in returning ReadAndWriteFiles.class object but it is throwing an error for KafkaProducer.class. on line
PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer);
Is there any other way to for this work around? Any suggestion will be appreciated.
Note: KafkaProducer.class is in not a custom class but its inside from apache spark kafka libraries
Main code is as per below
KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);
InputData inputMessage;
try {
inputMessage = populateData(timeStamp, dataCategory, data, atmId, topic);
ReadAndWriteFiles readerWriter = new ReadAndWriteFiles();
File[] directory = readerWriter.getAllFiles();
if (directory != null && directory.length > 0) {
if (connectionSet && !publishingData) {
sendDataFromFiles(producer, directory);
publishingData = false;
}
} else {
producer.send(keyedMsg, new KafkaResponseHandler(inputMessage));
}
} catch (IOException e) {
}
I think the error is
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(mockProducer)
I think the returned value should be a mock for ReadAndWriteFiles class not a KafkaProducer
ReadAndWriteFiles readMock = Mockito.mock(ReadAndWriteFiles.class)
PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(readMock)
Mockito.when(readMock.getAllFiles()).thenReturn(anArrayOfFiles);
The signature of the thenReturn method is as follow
OngoingStubbing<T> [More ...] thenReturn(T value);
So you are using to return a ReadAndWriteFiles you shouls return an object of the same class

OrientDB ClassCastException

I get the following exception when trying to access a relationship document:
java.lang.ClassCastException: com.orientechnologies.orient.core.id.ORecordId cannot be cast to com.orientechnologies.orient.core.record.impl.ODocument
via:
Collection<ODocument> field = myDoc.field("MY_FIELD_NAME");
if(field != null) {
return field;
} else {
return Collections.emptySet();
}
The strange thing is that is happes not always, most of the time it works like expected.
Depending by what the field contains, you could use the interface OIdentifiable instead of ODocument.
Try using:
Collection<OIdentifiable> field = myDoc.field("MY_FIELD_NAME");
if(field != null) {
return field;
} else {
return Collections.emptySet();
}

CRM 2011 development: Get the following error if I try to get related entity: Object reference not set to an instance of an object

I try to get a related entity and get this error: Object reference not set to an instance of an object.
See below my code:
public IEnumerable<RUBAnnotation> GetAnnotationsByServiceRequestId(string serviceRequestId)
{
List<Annotation> annotationList = new List<Annotation>();
try
{
using (OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(organisationWebServiceUri, null, userCredentials, deviceCredentials))
{
organizationProxy.EnableProxyTypes();
var service = (IOrganizationService)organizationProxy;
OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
Relationship rel = new Relationship("Incident_Annotation");
// get all incidents by incidentId
IEnumerable<Incident> incidents = from c in orgContext.CreateQuery<Incident>()
where c.Id == new Guid(serviceRequestId)
select c;
return GetAnnotationsEntities(incidents);
}
}
catch (Exception)
{
throw;
}
return null;
}
private List<RUBAnnotation> GetAnnotationsEntities(IEnumerable<Incident> incidents)
{
List<RUBAnnotation> annotationsList = new List<RUBAnnotation>();
try
{
foreach (Incident incident in incidents)
{
foreach (var annotation in incident.Incident_Annotation) // HERE OCCURS THE EXCEPTION!!
{
if (!string.IsNullOrEmpty(annotation.NoteText))
{
var customAnnotation = new RUBAnnotation();
customAnnotation.Id = annotation.Id.ToString();
if (annotation.Incident_Annotation != null)
{
customAnnotation.ServiceRequestId = annotation.Incident_Annotation.Id.ToString();
}
customAnnotation.Message = annotation.NoteText;
customAnnotation.CreatedOn = (DateTime)annotation.CreatedOn;
customAnnotation.UserId = annotation.CreatedBy.Id.ToString();
annotationsList.Add(customAnnotation);
}
}
}
}
catch (Exception e)
{
throw e;
}
return annotationsList;
}
Why do I get this error when I try to get incident.Incident_Annotation ? I think incident.Incident_Annotation is NULL, but why? Al my incidents have minimal 1 or more annotations.
Related entities must be explicitly loaded, you can find more information on this MSDN article:
MSDN - Access Entity Relationships

XmlSchemaInfo.SchemaElement is null after validation with reciving PVSI

I try to validate XDocument with compiled (and correct) schema set and with providing post validation schema info (PVSI):
public void ValidateDoc(XDocument doc)
{
if (doc == null)
return;
// _schema is correct filled schema-set
if (!_schemas.IsCompiled)
_schemas.Compile();
try
{
_validated.Clear();
if (_schemas.Count > 0)
doc.Validate(_schemas, OnValidate, true);
foreach (var item in _validated)
{
var si = item.GetSchemaInfo();
// si exists and si.Validity is set to XmlSchemaValidity.Invalid but si.SchemaElement and si.SchemaAttribute is null
}
}
catch (XmlSchemaException err)
{
_log.FatalException(string.Format("Failed to validate document {0} [{1}, {2}] ", doc.BaseUri, err.LineNumber, err.LinePosition), err);
}
}
protected virtual void OnValidate(object sender, ValidationEventArgs args)
{
if (ValidationEvent != null)
ValidationEvent(sender, args);
var xobj = sender as XObject;
if (xobj != null)
{
xobj.AddAnnotation(new XmlErrInfo(args));
if (xobj is XElement)
_validated.Add((XElement)xobj);
}
}
But .GetSchemaInfo().SchemaElement is null (and other fields its empty too), instead of point to compiled schema element (I need to use it in future validation scenarios of same elements). What's wrong with it or what I doing wrong?
Well if you wanted to access the SchemaElement of valid elements I could understand your approach but you seem to want to access the SchemaElement of those invalid elements reported to the event handler. I don't think those properties are populated for invalid nodes.

Resources