Home > database >  Unable to access variables from another project
Unable to access variables from another project

Time:03-03

I am trying to automate API testing using c# (Restsharp). I have 2 projects in same solution. One project is a console app where I am trying to keep the methods, while the other one is a Unit Test Project where I plan on keeping the test cases.

I am able to access the methods from the BASE project by creating an object of the method, but unable to access the variables within that method to apply assertions. Any idea what am I missing? (I am new to c#).

Method class in Base project

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using RestSharp;


namespace Base
{
    public class Methods
    {
        
        public void GetMethod(long ID)
        {
            var client = new RestClient("getUrl");
            var request = new RestRequest(Method.GET);
            request.AddParameter("userId", ID);
            IRestResponse response = client.Execute(request);
            HttpStatusCode statusCode = response.StatusCode;
            int nStatusCode = (int)statusCode;

        }
    }
}

UnitTest class in Test project

using System;
using System.Net;
using Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RestSharp;

namespace Tests
{
    [TestClass]
    public class UnitTests
    {
       

        [TestMethod]
        public void StatusOK()
        {
            //Arrange, Act, Assert
            var methods = new Methods();
            methods.GetMethod(2330013)
           Assert.IsTrue(nStatusCode.Equals(200));

           

        }
    }
}

UnitTest is unable to read nStatusCode variable, as well as response variable. I have already added dependency between the projects. Appreciate the help!!

CodePudding user response:

One option to address the problem is to make GetMethod return the status code:

public int GetMethod(long ID)
        {
            ...
            int nStatusCode = (int)statusCode;
            return nStatusCode;
        }

Then the test can examine the return value.

var c = methods.GetMethod(2330013)
Assert.AreEqual(200, c);

PS. I recommend using Assert.AreEqual instead of Assert.IsTrue because in the case the code is not 200 the test failure output will contain the bad value. With IsTrue you will only know that it wasn't 200 but you won't know what it was.

  • Related