Я тестирую метод C # (ASP.NET MVC), который использовал log4net для ведения журнала, при отладке / выполнении модульного теста я не получал никаких записей. Но ведение журнала работает при запуске приложения.
Метод:
public class MeasureController: Controller
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MeasureController));
// GET: Measure
[Authorize]
public ActionResult ViewMeasures()
{
try
{
string info = this.Server.MachineName + " " + this.Request.Browser.Platform + " " + this.Request.Browser.Browser;
log.Info(info);
log.Info(Session["UserName"].ToString() + " is try to View Measures");
List<MeasureViewModel> measureViewModels = new List<MeasureViewModel>();
using (var bl = new MeasureLayer())
{
List<MeasureEntity> measure = bl.ViewMeasures();
if (measure != null)
{
measureViewModels = new List<MeasureViewModel>();
foreach (var item in measure)
{
measureViewModels.Add(new MeasureViewModel
{
Id = item.Id,
GoalName = item.GoalName,
Name = item.Name,
RatingMechanism = item.RatingMechanism,
Description = item.Description,
Archive = item.Archive,
LastUpdatedBy = item.LastUpdatedBy,
LastUpdatedDate = item.LastUpdatedDate,
});
}
}
}
ViewBag.Message = "All Measure List.";
log.Info(Session["UserName"].ToString() + " is successfully view Measures List.");
return View(measureViewModels);
}
catch (Exception ex)
{
log.Fatal("Eroor occurs with configuration. " + ex.Message);
return View();
}
}
}
Метод модульного тестирования:
public class MeasureControllerTest
{
protected static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MeasureControllerTest));
MeasureController controller = new MeasureController();
[TestMethod]
public void ViewMeasuresReturnsValidDataWithNormalUser()
{
var appender = new log4net.Appender.MemoryAppender();
BasicConfigurator.Configure(appender);
log4net.Config.XmlConfigurator.Configure();
//create mock of HttpServerUtilityBase
var server = new Mock<HttpServerUtilityBase>(MockBehavior.Loose);
var response = new Mock<HttpResponseBase>(MockBehavior.Loose);
var request = new Mock<HttpRequestBase>(MockBehavior.Loose);
request.Setup(x => x.ApplicationPath).Returns("/");
request.Setup(x => x.Url).Returns(new Uri("http://localhost"));
request.Setup(x => x.Browser.Browser).Returns("Chrome");
request.Setup(x => x.Browser.Platform).Returns("WinNT");
request.Setup(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection{
{ "SERVER_NAME", "localhost" },
{ "SCRIPT_NAME", "localhost" },
{ "SERVER_PORT", "80" },
{ "REMOTE_ADDR", "127.0.0.1" },
{ "REMOTE_HOST", "127.0.0.1" }
});
MeasureController controller = new MeasureController();
string loginUser = "xyz@test.com";
string userIdentity = "User";
using (var ms = new MockSession())
{
Mock<HttpContextBase> mockContext = (Mock<HttpContextBase>)ms.GetMockSessionContext(loginUser, userIdentity);
mockContext.SetupGet(x => x.Request).Returns(request.Object);
mockContext.SetupGet(x => x.Server).Returns(server.Object);
mockContext.SetupGet(x => x.Server.MachineName).Returns("LAPTOP-100");
controller.ControllerContext = new ControllerContext()
{
Controller = controller,
RequestContext = new RequestContext(mockContext.Object, new RouteData())
};
}
ViewResult result = controller.ViewMeasures() as ViewResult;
var logEntries = appender.GetEvents();
var model = (List<MeasureViewModel>)result.ViewData.Model;
var expectedtype = new List<MeasureViewModel>();
//Assert.IsTrue(logEntries.Any());
Assert.AreEqual(expectedtype.GetType(), model.GetType());
}
}
Web.config
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<log4net>
<root>
<level value="ALL"></level>
<appender-ref ref="RollingLogFileAppender"></appender-ref>
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log/PMSAppLogReport.log" />
<appendToFile value="true" />
<rolingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%identity] %location %method %line [%thread] %level - %exception - %message%newline" />
</layout>
</appender>
</log4net>
App.config
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<log4net>
<root>
<level value="ALL"></level>
<appender-ref ref="RollingLogFileAppender"></appender-ref>
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log/PMSAppLogReport.log" />
<appendToFile value="true" />
<rolingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%identity] %location %method %line [%thread] %level - eventID:%property{eventID} %exception - %message%newline" />
</layout>
</appender>
</log4net>
Global.asax
log4net.Config.XmlConfigurator.Configure();
AssemblyInfo.cs (в модульном тесте)
[assembly: log4net.Config.XmlConfigurator()]
Я искал в Интернете / SO, но у меня пока нет решения. Любая помощь приветствуется.