0

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;
    }

1 Answer 1

1

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();
    }   
}
Sign up to request clarification or add additional context in comments.

2 Comments

That will save me a line before each unit test. But I was thinking dependency Injection or something I suppose.. I don't really understand it but I feel like there must be a better way to not have to repeat the code in the constructor
Or in other words... ctx = tf.GetContext(); could instead be ctx = tf.TheConstructor; but that does not work since the constructor does not return a Context object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.