Salesforce APEX Unit Test Error with REST Services / Error at SELECT of Case Object - unit-testing

I've succeeded to successfully construct a REST API using APEX language defined with an annotation: #RestResource.
I also wrote a matching Unit test procedure with #isTest annotation. The execution of the REST API triggered by a HTTP GET with two input parameters works well, while the Unit Test execution, returns a "null" value list resulting from the SOQL query shown below:
String mycase = inputs_case_number; // for ex. '00001026'
sObject[] sl2 = [SELECT Id, CaseNumber FROM Case WHERE CaseNumber = :mycase LIMIT 1];
The query returns:
VARIABLE_ASSIGNMENT [22]|sl2|[]|0x1ffefea6
I've also tried to execute it with a RunAs() method (see code below), using a dynamically created Salesforce test user, not anonymous, connected to a more powerful profile, but still receiving a "null" answer at the SOQL query. The new profile defines "View All" permission for Cases. Other SOQL queries to objects like: "User" and "UserRecordAccess" with very similar construction are working fine, both for REST APEX and Test APEX.
Is there a way to configure an access permission for Unit test (#isTest) to read the Case object and a few fields like: Id and CaseNumber. Is this error related to the "Tooling API" function and how can we fix this issue in the test procedure?
Code attachment: Unit Test Code
#isTest
private class MyRestResource1Test {
static testMethod void MyRestRequest() {
// generate temporary test user object and assign to running process
String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '#testorg.com';
Profile p = [SELECT Id FROM Profile WHERE Name='StandardTestUser'];
User pu = new User(Alias='standt',Email='standarduser#testorg.com',LastName='testing',EmailEncodingKey='UTF-8',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId=p.Id,TimeZoneSidKey='America/New_York',UserName=uniqueUserName);
System.RunAs(pu) {
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/sfcheckap/';
req.addParameter('useremail','testuserid#red.com');
req.addParameter('casenumber','00001026');
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = res;
System.debug('Current User assigned is: ' + UserInfo.getUserName());
System.debug('Current Profile assigned is: ' + UserInfo.getProfileId());
Test.startTest();
Map<String, Boolean> resultMap = MyRestResource1.doGet();
Test.stopTest();
Boolean debugflag = resultMap.get('accessPermission');
String debugflagstr = String.valueOf(debugflag);
System.assert(debugflagstr.contains('true'));
}
}
}

Found a solution path by using: #isTest(SeeAllData=true)
See article: "Using the isTest(SeeAllData=true) Annotation"
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_seealldata_using.htm

Related

Not able to pre populate the custom field using c# code in HelloSign

I was trying to pre-populate the custom field value from C# code but I was not able to. I have used following snippet of code to do so
var client = new Client("MY API KEY");
var request = new TemplateSignatureRequest();
request.AddTemplate("docID");
request.Title = "Test Titel";
request.Subject = "Test Subject";
request.Message = "Test Message.";
request.AddSigner("Me", "xxxxx#example.com", "Test");
request.AddSigner("Client", "xxxxx#example.com", "Test");
var firstName = request.GetCustomField("FirstName");
firstName.Value = "John";
request.TestMode = true;
var response = client.SendSignatureRequest(request);
I have already assigned the customer field to me and verified the API ID key for the field also.But still not able to get the result. Is there anything else we need to add to so that value John will be shown.
Try
request.AddCustomField("fName", "Alex");
Also, please feel free to reach out to apisupport#hellosign.com for more assistance if you would like.

Cannot query fromSql method with Entity Framework Core

I started a asp.net core project, using EF core 2.0.1.
I was able to migrate a database successfully to the project and generated partial class as follows
public partial class ManagementContext : DbContext
{
public virtual DbSet<Result> Results { get; set; }
}
I'm able to connect to the database and get db and get the all records in the db by assigning:
var results = dbContext.Results.ToList();
However when trying to assign by .fromSql() method i get error:
invalidlidOperationException: 'The required column 'Id' was not present in the results of a 'FromSql' operation.'
The errors is received in both of the following queries (get_results is a stored procedure that returns records of Result:
var resultsThroughRawQuery = dbContext.Results.FromSql("select * from dbo.Results").ToList();
var resultsThroughStoredProcedure = dbContext.Results.FromSql("EXEC get_results").ToList();
Result indeed has an Id columnm which is the key.
Is there something I miss here?

Rally Web Services API: How do I get the URL link of the user story? (getDetailUrl() method)

Please be patient and Do Not flag this as duplicate: Using the Rally REST API, how can I get the non-API (website) URL for a user story?
I want to be able to generate a link for the user story.
Something like this: https://rally1.rallydev.com/#/-/detail/userstory/*********
As opposed to this: https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement/88502329352
The link will be integrated into another application for the managers to see the user story.
I did read about the getDetailUrl() method, but in my case I am creating the user stories by parsing email and linking that to a notification service in Slack.
I am aware of the formattedID and (_ref), but I would have to query for it again, and I am creating batches of userstories through a loop. I need the actual web site link to the user story.
Here is my sample code:
public void CreateUserStory(string workspace, string project, string userstoryName){
//authenticate with Rally
this.EnsureRallyIsAuthenticated();
//DynamicJsonObject for HierarchicalRequirement
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate[RallyConstant.WorkSpace] = workspace;
toCreate[RallyConstant.Project] = project;
toCreate[RallyConstant.Name] = userstoryName;
try
{
//Create the User Story Here
CreateResult createUserStory = _api.Create(RallyConstant.HierarchicalRequirement, toCreate);
Console.WriteLine("Created Userstory: " + "URL LINK GOES HERE");
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
}
We don't have a method in the .NET toolkit for doing this, but it's easy to create.
The format is this:
https://rally1.rallydev.com/#/detail/<type>/<objectid>
Just fill in the type (hierarchicalrequirement turns into userstory, but all the others are the same as the wsapi type) and the objectid from the object you just created.
var parameters = new NameValueCollection();
parameters["fetch"] = "FormattedID";
var toCreate = new DynamicJsonObject();
var createResult = restApi.create("hierarchicalrequirement", toCreate, parameters);
var type = Ref.getTypeFromRef(createResult.Reference);
var objectID = Ref.getOidFromRef(createResult.Reference);
var formattedID = createResult.Object["FormattedID"];
And you can specify fetch fields to be returned on the created object so you don't have to re-query for it.

how to mock/stub out a specific custom validator when doing unit testing in grails?

Lets say i have a domain A which has a custom validator for property P
static constraints = {
P validator: { val, obj ->
(A.executeQuery("SELECT COUNT(*) FROM A cei WHERE cei.event.id = ?", [val.id])[0] <= 1)
}
In the unit test how can i mock the P property of domain A so that i don't get the error i am getting when running unit test. The error i get when running unit test is shown below. The setup code instantiates domain A as shown below.
void setUp(){
inv = new A(P: rg).save(flush: true)
Error is
java.lang.UnsupportedOperationException: String-based queries like [executeQuery] are currently not supported in this implementation of GORM. Use criteria instead.
Note: These are fake code.
The best option for me, is encapsulate the inner code of the validator inside a service. And then, mock that service in your unit test.
But the error thrown is that executeQuery is not available, but criteria is.
So change your code for using a criteria instead.
P validator: { val, obj ->
A.withCriteria{
eq('event', Event.findById(val.id))
projections{
count('id')
}
}[0] < = 1
}

Salesforce - Data type for webservice response

Im trying to execute/consume a webservice and wondering if I am using the correct data type to return the results. String seems to work, but I receive an empty string. The service should be returning a simple string value without XML. There is a working version written in JS below, I have been asked to recreate it in Apex.
JS version (Working) - executed when a button is clicked
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
var xfolder = "TestFolder"
var parentid = "22K22"
var myvar = sforce.apex.execute("myWS","invokeWs", {folderName:xfolder,ObjectID:parentid});
window.alert('LiveLink folder created: ' + myvar);
APEX version (not working)
public with sharing class myTest {
public String getWSXMLResult() {
String tmpFolderName2 = 'TestFolder';
String tmpObjectID2 = '22K22';
String myWSXMLResult = myWS.invokeWs(tmpFolderName2,tmpObjectID2);
System.debug('XIXWS|' + myWSXMLResult);
return myWSXMLResult;
}
}
One thing I just noted while typing this out. I didn't specify the argument names for invokeWs, just the values..do I need to specify those values in the call to the WS? Such as..
myWS.invokeWs(folderName=tmpFolderName2,ObjectID=tmpObjectID2); -- this errors out btw
Thanks again everyone.