How to Mock OperationContext

4 posts, 0 answers
  1. Gopala
    Gopala avatar
    2 posts
    Member since:
    Apr 2013

    Posted 17 Apr 2013 Link to this post

    Hi there,
    I am testing method that inserts data into a table in the database and returns the ID.
    My class(not the test class business logic class) is no way related to any wcf service but after inserting data my method calling context.savechanges() method then its validating my credentials. For the validation I have validation.cs. There its checking the headers
    in the operation context. Is there anyway to get around the OperationContext. I am using JustMock 30 day Trial version. I tried the following code

     IContextChannel channel = null;

                var context = Mock.Create<OperationContext>(()=>new OperationContext(channel));
                OperationContext.Current = context;
                MessageHeader header = MessageHeader.CreateHeader(CustomHeader.Header, CustomHeader.HeaderNamespace, customHeader);
                Mock.Arrange(() => context.OutgoingMessageHeaders.Add(header));
    I have been trying to solve this for the last 2 days.
    Thank so much for ur help in advance
  2. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 18 Apr 2013 Link to this post

    Hi Gopala,

    Thank you for contacting Telerik support.

    To show you how "OperationContext" can be faked with JustMock, I prepared the following example:
    [TestMethod]
    public void ShouldMockOperationContextClass()
    {
        // Arrange
        var mock = Mock.Create<OperationContext>(Constructor.Mocked);
     
        Mock.Arrange(() => mock.SessionId).Returns("Telerik"); // Will arrange the "SessionId" property to return certain string ("Telerik").
        Mock.Arrange(() => OperationContext.Current).Returns(mock); // Will arrange the static "OperationContext.Current" to return mocked instance when called.
         
        // Act
        var actual = OperationContext.Current.SessionId;
     
        // Assert
        Assert.AreEqual("Telerik", actual); // Will assert the expected results
    }
    I hope the above helps.

    However, to assist you further with your certain scenario, I will need a sample project with the system under test. You can archive and attach it with your next message.

    You could also check our online help documentation. There are a lot of mocking examples, that should help.  

    Regards,
    Kaloyan
    the Telerik team
    Share what you think about JustTrace & JustMock with us, so we can become even better! You can use the built-in feedback tool inside JustTrace, our forums, or our JustTrace or JustMock portals.
  3. DevCraft R3 2016 release webinar banner
  4. Gopala
    Gopala avatar
    2 posts
    Member since:
    Apr 2013

    Posted 18 Apr 2013 Link to this post

    Hi there thank you so much for your help.
    It didn't really solve my problem. Please look at the following code:

    My TestClass

    [TestClass()]
     public class ClientTest
    {
    private static Service.CustomHeader customHeader = new CustomHeader { clientId = 3, userId = 1 };
    [ClassInitialize()]
            public static void MyClassInitialize(TestContext testContext)
            {
                var header = MessageHeader.CreateHeader(CustomHeader.HeaderXXXCustomHeader, CustomHeader.HeaderNamespace, customHeader);
                var context = Mock.Create<OperationContext>(Constructor.Mocked);           
                Mock.Arrange(() =>OperationContext.Current).Returns(context);
                Mock.Arrange(()=>context.OutgoingMessageHeaders.Add(header));
    }

    [TestMethod()]
            public void InsertTest()
            {
                
                int clientId = 0;
                DataObjects.Client client = new DataObjects.Client(); // TODO: Initialize to an appropriate value
                client.IsActive = true;
                client.Name = "TestInsertClient";
                client.Description = "InsertTest Test Client desc";

                clientId = new DataSources.Client().Insert(client);

                Assert.IsNotNull(clientId);

            }
    }

    My Business Logic Class

    namespace DataSources
     public class Client
     {
    public int Insert(DataObjects.Client client)
            {
                try
                {             

                    using (var context = new TestEntities())
                    {
                        context.ContextOptions.ProxyCreationEnabled = false;
                        context.Clients.AddObject(client);
                        context.ObjectStateManager.ChangeObjectState(client, EntityState.Added);
                        context.SaveChanges();

                        return client.ClientId;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(new ExceptionDefinition(ex.Message, ex));
                }
            }
    }

    My Validation.cs
    public partial class TestEntities
        {     
            public override int SaveChanges(SaveOptions options)
            {
                foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
                {
                    entry.CurrentValues.SetValue(entry.CurrentValues.GetOrdinal("ChangedBy"), OperationContext.Current.IncomingMessageHeaders.GetHeader<Service.CustomHeader>(Service.CustomHeader.HeaderCustomHeader, Service.CustomHeader.HeaderNamespace).userId);
                    entry.CurrentValues.SetValue(entry.CurrentValues.GetOrdinal("ChangedDateTime"), DateTime.Now);
                }

                return base.SaveChanges(options);
            }

        }

    The above is my whole lot of code.

    When i tried to run test I was getting "Object reference not set an instance of an object"
    What I want to do I want to mock OperationContext in my Test Class Intialize and I want to add header to the OperationContext.
    Thank you so much for your help.
  5. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 19 Apr 2013 Link to this post

    Hi again Gopala,

    Thank you for the code provided.

    However, is it possible for you to wrap it in a compiling project with all the references needed. You could attach it to your next ticket. This will let us investigate the issue much faster and accordingly solve it.

    Thank you for the understanding.

    Greetings,
    Kaloyan
    the Telerik team
    Share what you think about JustTrace & JustMock with us, so we can become even better! You can use the built-in feedback tool inside JustTrace, our forums, or our JustTrace or JustMock portals.
Back to Top