#json #salesforce #apex
Вопрос:
Я новичок в Apex и пытаюсь протестировать один из своих классов Apex, но только что получил охват 25%.
Я даже не думаю , что это действительно тестирование моего класса, потому что просто какое-то объявление переменной и какой-то оператор if после теста становятся синими. может быть, кто-нибудь здесь может дать мне какие-нибудь указания по этому поводу.
Итак, я позволил, скажем, классу JsonParser, который принимает Http-ответ в качестве параметра, и предполагается, что он находит определенные значения, чтобы построить один объект с именем crane.
Таким образом, у крана есть как поля:
Мой объект здесь представляет собой кран и имеет в качестве полей:
public class JsonToCranesParser {
public static List<Crane__c> JsonToCranes(HTTPResponse res) {
// create Parser
JSONParser parser = JSON.createParser(res.getBody());
// Define lists for my crane fields
List<String> Ids = new List<String>();
List<String> CraneType= new List<String>();
List<String> CraneCategory = new List<String>();
List<String> CraneControls= new List<String>();
List<String> LoadCapacityType_0= new List<String>();
List<String> TrackWidthCraneType_0= new List<String>();
List<String> EngineControl_0= new List<String>();
List<String> SellerCompany= new List<String>();
List<Double> DemontageNummer= new List<Double>();
List<Double> UsablePendulumStrutRadius= new List<Double>();
List<Double> UsableSolidStrutRadius= new List<Double>();
List<Double> LoadCapacityWeight_0= new List<Double>();
List<Double> TrackWidthCrane_0= new List<Double>();
List<String> strList= new List<String>{'craneType','craneCategory','craneControls','loadCapacityType_0','trackWidthCraneType_0','engineControl_0','sellerCompany'};
List<String> DblList= new List<String>{'dismantlingnumber','usablePendulumStrutRadius','usableSolidStrutRadius','loadCapacityWeight_0','trackWidthCrane_0'};
String tmp;
String tmp2;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) amp;amp; (parser.getText() == 'id')) {
while (parser.getText() != 'stringValue'){
parser.nextToken();
}
parser.nextToken();
Ids.add(parser.getText());
}
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) amp;amp; (strList.contains(parser.getText()))) {
tmp= parser.getText();
while (parser.getText() != 'value'){
parser.nextToken();
}
parser.nextToken();
parser.nextToken();
parser.nextToken();
switch on tmp {
when 'craneType' {
CraneType.add(parser.getText());
}
when 'craneCategory' {
CraneCategory.add(parser.getText());
}
when 'craneControls' {
CraneControls.add(parser.getText());
}
when 'loadCapacityType_0' {
LoadCapacityType_0.add(parser.getText());
}
when 'trackWidthCraneType_0' {
TrackWidthCraneType_0.add(parser.getText());
}
when 'engineControl_0' {
EngineControl_0.add(parser.getText());
}
when 'sellerCompany' {
SellerCompany.add(parser.getText());
}
}
}
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) amp;amp; (dblList.contains(parser.getText()))) {
tmp2= parser.getText();
while (parser.getText() != 'value'){
parser.nextToken();
}
parser.nextToken();
parser.nextToken();
parser.nextToken();
switch on tmp2 {
when 'dismantlingnumber' {
DemontageNummer.add(parser.getDoubleValue());
}
when 'usablePendulumStrutRadius' {
UsablePendulumStrutRadius.add(parser.getDoubleValue());
}
when 'usableSolidStrutRadius' {
UsableSolidStrutRadius.add(parser.getDoubleValue());
}
when 'loadCapacityWeight_0' {
LoadCapacityWeight_0.add(parser.getDoubleValue());
}
when 'trackWidthCrane_0' {
TrackWidthCrane_0.add(parser.getDoubleValue());
}
}
}
}
List<Crane__c> myCranes = new List<Crane__c>();
// we create a crane list with the data we get from the firestore database
for(Integer i = 0; i < Ids.size(); i ){
Crane__c myCurrentCrane = new Crane__c();
myCurrentCrane.firestore_id__c = Ids[i];
myCurrentCrane.Crane_Category__c = CraneCategory[i];
myCurrentCrane.Crane_Type__c = CraneType[i];
myCurrentCrane.CraneControls__c =CraneControls[i];
myCurrentCrane.Engine_Control__c = EngineControl_0[i];
myCurrentCrane.LoadCapacityType__c = LoadCapacityType_0[i];
myCurrentCrane.Track_Width_Crane_Type__c = TrackWidthCraneType_0[i];
myCurrentCrane.Seller_Company__c = SellerCompany[i];
myCurrentCrane.Demontage_Number__c = DemontageNummer[i];
myCurrentCrane.Load_Capacity_Weight__c = LoadCapacityWeight_0[i];
myCurrentCrane.Track_Width_Crane__c = TrackWidthCrane_0[i];
myCurrentCrane.Usable_Pendulum_Radius__c = UsablePendulumStrutRadius[i];
myCurrentCrane.Usable_Solid_Radius__c = UsableSolidStrutRadius[i];
myCranes.add(myCurrentCrane);
}
System.debug('Ids: ' Ids);
System.debug('CraneType: ' CraneType);
System.debug('CraneCategory: ' CraneCategory);
System.debug('CraneControls: ' CraneControls);
System.debug('LoadCapacityType_0: ' LoadCapacityType_0);
System.debug('TrackWidthCraneType_0: ' TrackWidthCraneType_0);
System.debug('EngineControl_0: ' EngineControl_0);
System.debug('SellerCompany: ' SellerCompany);
System.debug('DemontageNummer: ' DemontageNummer);
System.debug('UsablePendulumStrutRadius: ' UsablePendulumStrutRadius);
System.debug('UsableSolidStrutRadius: ' UsableSolidStrutRadius);
System.debug('LoadCapacityWeight_0: ' LoadCapacityWeight_0);
System.debug('TrackWidthCrane_0: ' TrackWidthCrane_0);
List<Crane__c> SalesForceCranes = new List<Crane__c>();
SalesForceCranes= [SELECT Id, firestore_id__c FROM Crane__c];
// As we want to upsert cranes, we have to get their Saleforce Id if they already exist in Salesforce
for(Crane__c var1 : myCranes){
for(Crane__c var2 : SalesForceCranes){
if (var1.firestore_id__c == var2.firestore_id__c) {
var1.Id=var2.Id;
}
}
}
upsert myCranes;
return myCranes;
}
}
и в моем тестовом классе я создаю тестовые данные в качестве Http-ответа, и дело в том, что обычно после запуска метода моего класса я хочу сравнить, являются ли возвращаемые значения ожидаемыми, как это
@isTest (SeeAllData=true)
публичный класс JsonToCranesParserTest {
@isTest static void testJsonToCranes() {
//Test.setMock(HttpCalloutMock.class, new MockJsonBodyGenerator());
//HTTPRequest req =new HTTPRequest();
// HTTPResponse res= new MockJsonBodyGenerator().respond(req);
HTTPResponse res= new HttpResponse();
res.setBody('"id": {'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"stringValue": "IdValue1"'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"craneType": {' '"value": {' '"stringValue": "craneTypeValue1"'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"craneCategory":{' '"value": {' '"stringValue": "craneCategoryValue1"'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"craneControls":{' '"value": {' '"stringValue": "craneControlsValue1"'
'"loadCapacityType_0":{' '"value": {' '"stringValue": "loadCapacityType_0Value1"'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"trackWidthCraneType_0":{' '"value": {' '"stringValue": "trackWidthCraneType_0Value1"'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"engineControl_0": {' '"value": {' '"stringValue": "engineControl_0Value1"'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"sellerCompany": {' '"value": {' '"stringValue": "sellerCompanyValue1"'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"dismantlingnumber": {' '"value": {' '"doubleValue": 10'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"usablePendulumStrutRadius": {' '"value": {' '"doubleValue": 11'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"usableSolidStrutRadius": {' '"value": {' '"doubleValue": 12'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"loadCapacityWeight_0": {' '"value": {' '"doubleValue": 13'
'"FakeType": {' '"Fake": {' '"FakeValue": "FakeValue1"'
'"trackWidthCrane_0": {' '"value": {' '"doubleValue": 14');
// Call method to test.
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
//
List<Crane__c> cranes = JsonToCranesParser.JsonToCranes(res);
// Verify response received contains fake values
for(Crane__c var1 : cranes){
System.assertEquals(var1.firestore_id__c, 'IdValue1');
System.assertEquals(var1.Crane_Category__c, 'craneCategoryValue1');
System.assertEquals(var1.Crane_Type__c, 'craneTypeValue1');
System.assertEquals(var1.CraneControls__c, 'craneControlsValue1');
System.assertEquals(var1.Engine_Control__c, 'engineControl_0Value1');
System.assertEquals(var1.LoadCapacityType__c, 'loadCapacityType_0Value1');
System.assertEquals(var1.Track_Width_Crane_Type__c, 'trackWidthCraneType_0Value1');
System.assertEquals(var1.Seller_Company__c, 'sellerCompanyValue1');
System.assertEquals(var1.Demontage_Number__c, 10);
System.assertEquals(var1.Load_Capacity_Weight__c, 13);
System.assertEquals(var1.Track_Width_Crane__c, 14);
System.assertEquals(var1.Usable_Pendulum_Radius__c, 11);
System.assertEquals(var1.Usable_Solid_Radius__c , 12);
}
}
}
Пожалуйста, какой-нибудь совет?
Комментарии:
1. Если вы видите какие-либо линии, покрытые синим, в вашем классе, это покрывает его. Скорее всего, есть что-то, что заставляет ваш код возвращаться. Просмотрите последнюю синюю строку и посмотрите, сможете ли вы определить, что может заставить ваш код остановиться.
2. Кроме того, преобразуйте свой идентификатор firestore_id во внешнее уникальное поле идентификатора. Если вы сделаете это, вы можете просто выполнить «upsert myCranes firestore_Id__c» и удалить запрос и цикл, который пытается найти существующую запись.