简体   繁体   中英

How to share class variable between a unit test and another class?

How can I avoid having to call this extra method when running my unit test? I want somehow to have that context object created in the constructor to be used in the unit test

  [TestMethod]
    public void Delete_Sp_List()
    {
        ctx = tf.GetContext();
        List list = ctx.Web.Lists.GetByTitle("StackTicketList");
        list.DeleteObject();
        ctx.ExecuteQuery();
    }


   public TicketForm()
    {
        SecureString ssPwd = new SecureString();
        strPassword.ToList().ForEach(ssPwd.AppendChar);
        SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(strUserName, ssPwd);
        ctx.Credentials = credentials;
    }

    public ClientContext GetContext()
    {
        SecureString ssPwd = new SecureString();
        strPassword.ToList().ForEach(ssPwd.AppendChar);
        SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(strUserName, ssPwd);
        ctx.Credentials = credentials;

        return ctx;
    }

You should look at [TestInitilize] attribute. You can create a method (void Init() {...})and mark it with this attribute. This method will be called before the execution of each test method. By placing your initialization logic in Init method you can avoid copying this logic between test methods

[TestClass]
public class Test
{
    private ClientContext ctx;


    [TestInitialize]
    public void Init()
    {
        ctx = GetContext();
    }

    [TestMethod]
    public void Delete_Sp_List()
    {
        List list = ctx.Web.Lists.GetByTitle("StackTicketList");
        list.DeleteObject();
        ctx.ExecuteQuery();
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM