Wednesday, April 22, 2020

[Code Snippet] Assert Exception in private methods using PrivateObject

NON ASYNC Method

Method.cs

private MyMethod(object value1)
{
      if(value1 == null)
      {
           throw new ArgumentNullException(nameof(MyMethod));
      }
}

Test.Cs

[TestMethod]
public void MyMethod_Throws_Verify()
{
         PrivateObject po = new PrivateObject(new Method())

TargetInvocationException exception = Assert.ThrowsException<TargetInvocationException>(() =>
                    privateObject.Invoke("MyMethod", new object[] { null }));

            Assert.AreEqual(typeof(ArgumentNullException), exception.InnerException.GetType());
       
}




ASYNC METHOD

MethodAsync.cs
private async MyMethod(object value1)
{
      if(value1 == null)
      {
           throw new ArgumentNullException(nameof(MyMethod));
      }
}

TestAsync.cs

[TestMethod]
public async Task MyMethod_Throws_Verify()
{
         PrivateObject po = new PrivateObject(new Method())

var exception = await Assert.ThrowsExceptionAsync<TargetInvocationException>( async () =>
                    privateObject.Invoke("MyMethod", new object[] { null }));

            Assert.AreEqual(typeof(ArgumentNullException), exception.InnerException.GetType());
     
}












.NET , C# , Unit Test

1 comment :

 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me