chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
Using the community verison of TypeMock and attempting to mock the following:
public interface IFileUpload
{
   string SaveChanges();
}

public abstract class MyControl : System.Web.UI.UserControl
{
   public new MyPage Page { get (return (MyPage)base.Page; }
}

public abstract class MyPage : Page 
{
   public static MyPage Current
   {
      get {return HttpContext.Current.Handler as MyPage;}
   }
   public bool Validate(bool badCondition, string errorMessage)
   {
      //do validation test
      return true;
   }
}

public partial class FileUpload : MyControl, IFileUpload
{
    public string SaveChanges()
    {
   this.Page.Validate(..., ...);
   return "";
    }
}

[TestFixture]
[ClearMocks]
class UserControlInterfacesTest
{
   [Test]
   [VerifyMocks]
   public void FileUploadTest()
   {
      IFileUpload fileUpload = new FileUpload();
      Assert.IsTrue(fileUpload.SaveChanges() == "");
   }
}

I hope that all makes sense as I'm a beginner and I've stripped out some unnecessary code.

The issue I'm having is mocking the "Page" property which is actually a property of the abstract class "MyPage" and returns a casted instance of the System.Web.UI.Page property in the System.Web.UI.Control class.

I can mock "Validate" fine because it belongs to the abstract OurPage class.
asked by rockitsauce (640 points)

2 Answers

0 votes
Hi
You got few tools in hand which let you do what you want.
1. To mock interfaces and abstract classes use MockManager.MockObject.
2. Remember that by default mock objects abstract class are strict! (Means you have to expect every call)
3. To Mock Properties use Mock.ExpectGet and Mock.ExpectSet methods.

Here is an example how to do it:
[Test]
public void Test()
{
   //mock MyControl - we  want to mock its Page property
   MockObject mockMyControl = MockManager.MockObject(typeof(MyControl));
   //mock MyPage - we are going to use it to return a value from MyControl.Page
   MockObject mockMyPage = MockManager.MockObject(typeof (MyPage));

   //All calls are strict so we have expect Validate
   mockMyPage.ExpectUnmockedCall("Validate");
   mockMyControl.ExpectGet("Page", mockMyPage.Object);

   MyControl myControl = mockMyControl.Object as MyControl;
   MyPage pg = myControl.Page;

   //this is just to show that you really got MyPage instance in your hands ...
   Assert.IsTrue(pg.Validate(false, ""));
   MockManager.Verify();
}


Hope it helps. Please tell me if you have more questions.
answered by ohad (35.4k points)
0 votes
This is exactly what I was looking for. Thanks.
answered by rockitsauce (640 points)
...