-1

This is My first Unit test in visual studio 2013. First, I create one web application and then I added one new project as unit test. Then in my project I added log4net. Like, Web application webconfig

<log4net>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
  <!--<param name="File" value="LOG/Interview_LogFile.txt"/>-->
  <file type="log4net.Util.PatternString" value="%property{LogFileName}" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10000" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <!--<param name="ConversionPattern" value="%date [%thread] : %method %level %logger - %message%newline%exception"/>-->
    <param name="ConversionPattern" value="%date [%thread] : %message%newline%exception" />

  </layout>
</appender>

<root>
  <level value="ALL" />
  <appender-ref ref="LogFileAppender" />
</root>

My Project File image project solution

enter image description here

Testcase Testcase enter image description here

That log4net worked with web application, but unit test class file is not working what can I do??

Yogi
  • 9,174
  • 2
  • 46
  • 61
  • 1
    What's the purpose to using the logger with the unit tests like that? – David Arno Jan 04 '16 at 12:39
  • 1
    if testcase files means i no need to check in code.if i refer log file means i can get clear idea – Malathi Lakshmi Jan 04 '16 at 12:40
  • 3
    You need to update your question with your test case code (especially as you've removed the image link). It can't be answered as is. Using a logger to record the results of unit tests misses the point of the tests. – David Arno Jan 04 '16 at 12:43
  • 1
    Do you want to achieve something like [this](http://stackoverflow.com/questions/23446/how-do-i-format-visual-studio-test-results-file-trx-into-a-more-readable-form)? – mbm Jan 05 '16 at 02:29
  • 1
    No I added app config file and config the log4net config but I can't achieve – Malathi Lakshmi Jan 05 '16 at 05:45

3 Answers3

1

Your logger configuration is in web.config file, so these settings will only be available in the context of your web application.

When you run your test project, it has a different context, and it do not understand the web.config file which is there in you web application project.

To overcome this you need to add an app.config file to your unit test project and replicate the logger setting in that file.

Yogi
  • 9,174
  • 2
  • 46
  • 61
  • can i add global.cs file – Malathi Lakshmi Jan 04 '16 at 13:19
  • @MalathiLakshmi - Adding global.cs file will not make any differenct, infact you cannot add one in unit test project, because it is a class library. Simply right click your unit project >> Add "Application Configuration File" and name it appropriate e.g. app.config >> And in the `configuration` simply copy your log4Net configuration. Your code should work fine then. – Yogi Jan 04 '16 at 14:05
0

Currently, you have a unit test method that appears to be testing that the type of a string variable is a string. The only way for your test to fail is if it isn't a string. If any exception occurs, you hide it from the test, so the test will think it passed correctly.

The unit test framework relies on tests throwing exceptions, or assertions failing, for it to detect failing tests. So you should not have the try/catch inside your code, as that prevents the framework doing its job. Also, the framework will log test failures and report them to you. You should not be trying to use a different logger to do that.

To get your test working:

  1. Give it a proper name. UnitTest1 reveals nothing about the purpose of the test.
  2. Remove the try/catch and the logger.*** lines.
  3. Devise a proper Assert.*** that tests the result of methodobj in a meaningful way (eg, that it reports a success for valid loginvalidation call and a failure for an invalid one).
David Arno
  • 42,717
  • 16
  • 86
  • 131
0

Wishing to automatically save the unit test 'output' which is normally only available via the Test Explorer window, I think I have another solution, shown below:

/// <summary>
/// Test Logger. 
/// </summary>
/// <remarks>
/// Build unit test code as follows:
/// <code>
/// using TestCommon;
/// [TestClass]
/// public class MyTestClass {
/// 
/// // This property & static MUST be inside your [TestClass]
/// public Microsoft.VisualStudio.TestTools.UnitTesting.TestContext TestContext
/// {   get { return context; }
///     set { context = value; } }
/// private static TestContext context = null;
/// private static TestLogger log = null;
/// [ClassInitialize]
/// public void Initialize() {
///     log = new TestLogger(logFileName);  // provide a path\name
/// }
/// 
/// [TestMethod]
/// public void MyTest()
/// {
///     try {
///         log.Open(context);
///         ... // perform a test
///         log.Info("time: {0} Iteration {1}", Now, i);
///     } catch (AssertFailedException ex)
///         log.Exception(ex);
///         throw;
///     } finally {
///         log.Close();
///     }
/// }
/// </code>
/// </remarks>
public class TestLogger
{
    private static TestContext context = null;

    private string logfilename = null;
    private TextWriterTraceListener writer = null;
    private DataCollectorMessageLevel errorLevel = DataCollectorMessageLevel.Info;

    /// <summary>
    /// Microsoft.VisualStudio.TestTools.Common.DataCollectorMessageLevel
    /// Levels: Error, Warning, Info (default), Data
    /// </summary>
    public DataCollectorMessageLevel ErrorLevel
    {
        get { return errorLevel; }
        set { errorLevel = value; }
    }

    /// <summary>
    /// Create the logger. Set up work in Class initializer, it should also work inside each test.
    /// </summary>
    /// <param name="logfile">Path to the file to log into</param>
    public TestLogger(string logfile, bool update = true)
    {
        logfilename = logfile;
        errorLevel = DataCollectorMessageLevel.Info;
        if (!update)
            try { System.IO.File.Delete(logfile); } catch { }
        writer = new TextWriterTraceListener(logfilename);
        Debug.Listeners.Add(writer);
        Debug.AutoFlush = true;

        if (context != null)
        {
            Debug.WriteLine("Test Logger: {0} - {1}", context.FullyQualifiedTestClassName, context.TestName);
        }
    }

    /// <summary>
    /// At start of a test, it logs that information
    /// </summary>
    /// <param name="theContext">records context to access Test Name</param>
    public void Open(TestContext theContext)
    {
        context = theContext;
        Debug.WriteLine("Test Logger: {0} - {1}", context.FullyQualifiedTestClassName, context.TestName);
    }

    /// <summary>
    /// At end of a test. Best if put in a finally clause.
    /// </summary>
    public void Close()
    {
        if (context != null)
        {
            Debug.WriteLine("Test Ending: {0} - {1}", context.FullyQualifiedTestClassName, context.TestName);
        }
        Debug.WriteLine("");
    }


    /// <summary>
    /// The Logger functions use a standard string format 
    /// </summary>
    /// <param name="format"></param>
    /// <param name="parameters"></param>
    public void Data(string format, params object[] parameters)
    {
        if (errorLevel > DataCollectorMessageLevel.Data) return;
        Debug.WriteLine(format, parameters);
    }
    public void Info(string format, params object[] parameters)
    {
        if (errorLevel > DataCollectorMessageLevel.Info) return;
        Debug.WriteLine(format, parameters);
    }
    public void Warning(string format, params object[] parameters)
    {
        if (errorLevel > DataCollectorMessageLevel.Warning) return;
        Debug.WriteLine(format, parameters);
    }
    public void Error(string format, params object[] parameters)
    {
        if (errorLevel > DataCollectorMessageLevel.Error) return;
        Debug.WriteLine(format, parameters);
    }
    /// <summary>
    /// Able to include the Assert error message in the log
    /// </summary>
    /// <param name="ex">ex.Message is the Assert message, ex.ToString includes the call stack</param>
    public void Exception(Exception ex)
    {
        if (ex is AssertFailedException)
        {
            // ex.Message is only the Assertion text
            Debug.WriteLine(String.Format("{0}", ex.ToString()));
        }
        else
        {
            Debug.WriteLine(string.Format("{0}", ex.ToString()));
        }
    }
}

It works if you run or debug the tests I only wish context was known earlier so that the output could be placed in the \TestResults\ directory.

Henri Socha
  • 291
  • 2
  • 6