locked
using unit test for aspx code behind files

    Question

  • I raised this question in VSTS - Developers community and was advised to consult here, so posting my original question:

    Is there a way to write unit tests and get code coverage for aspx code behind files? I searched few forums but did not find an answer.

    And I'm not looking anything outside VSTS (like Nunit or something else), it should be integrated to VSTS and runnable after successful build.

    From one reply I got in Dev group is there is no way to have automated unit testing with code coverage possible for existing sites developed using ASP .NET 2.0 having traditional code behind files. Is this true?

    Hard to believe that even the topic of "How to: create an ASP .NET unit test" inside MSDN documentation talks about generating unit tests for class files inside App_code directory. What about the existing asp code behind files(aspx.cs) built on top of asp .net 2.0 and vs 2005?

    I'm looking for quick response here.

    Wednesday, August 23, 2006 9:02 PM

Answers

  • Hello Nikhil,

    While our test generation does not automatically generate accessors and tests for the aspx.cs files, you could still test that code inside an ASP.NET unit test. You may find the TestContext.RequestedPage very useful. E.g. this is my aspx.cs code:

    public partial class _Default : System.Web.UI.Page
    {
        public string Foo()
        {
            return "Hello";
        }
    }

    And respectively this is a sample code to test it:

        [TestClass()]
        public class Class1Test
        {
            private TestContext testContextInstance;
            public TestContext TestContext
            {
                get { return testContextInstance; }
                set { testContextInstance = value; }
            }
            [TestMethod()]
            [HostType("ASP.NET")]
            [AspNetDevelopmentServerHost("%PathToWebRoot%\\WebSite", "/WebSite")]
            [UrlToTest("http://localhost/WebSite")]
            public void ConstructorTest()
            {
                PrivateObject po = new PrivateObject(TestContext.RequestedPage);
                object res = po.Invoke("Foo");
                Assert.AreEqual("Hello", res, "Different result");
            }
        }

    I hope this helps,

     

    Tuesday, August 29, 2006 9:58 PM