+ Start a Discussion
Nihon TaisaiNihon Taisai 

Cannot specify Id in an insert call: [Id] in unit test for HttpPost

I have this error because I duplicate my object by method's calling. How can I fix it?

My HttpPost:
public static Avia__c ParseRequest(RestRequest req) {
    Avia__c a = new Avia__c();
    String body = req.requestBody.toString();
    a = (Avia__c)JSON.deserialize(body, Avia__c.class);
    return a;
global static Id doPost() {
    RestRequest req = RestContext.request;
    Avia__c a = ParseRequest(req);
    insert a;
    return a.id;
My test:
static void testPost() { 
    Avia__c testRecord = new Avia__c (Name = 'Name');
    String json = System.JSON.serialize(testRecord);
    RestRequest request = new RestRequest();
    request.requestBody = Blob.valueOf(json);
    request.httpMethod = 'POST';
    request.addHeader('Content-Type', 'application/json');
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/Job_Advertisement__c/' + testRecord.Id;
    RestContext.request = request;
    Avia__c ourRecord = Endpoint.ParseRequest(request);
    System.assertEquals(testRecord, ourRecord);

    Id tId = Endpoint.doPost();  //here is an error
    System.assertEquals(testRecord.Id, tId);
I just call the method and it inserts a record twice. So I become Id's conflict. How can I change it? Of caurse I can upsert it, but I also have a PUT method, so I don't need it in my POST.