【发布时间】:2015-06-19 20:50:05
【问题描述】:
我想用 Mock 测试一个 void 方法。
public class ConsoleTargetBuilder : ITargetBuilder
{
private const string CONSOLE_WITH_STACK_TRACE = "consoleWithStackTrace";
private const string CONSOLE_WITHOUT_STACK_TRACE = "consoleWithoutStackTrace";
private LoggerModel _loggerModel;
private LoggingConfiguration _nLogLoggingConfiguration;
public ConsoleTargetBuilder(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration)
{
_loggerModel = loggerModel;
_nLogLoggingConfiguration = nLogLoggingConfiguration;
}
public void AddNLogConfigurationTypeTagret()
{
var consoleTargetWithStackTrace = new ConsoleTarget();
consoleTargetWithStackTrace.Name = CONSOLE_WITH_STACK_TRACE;
consoleTargetWithStackTrace.Layout = _loggerModel.layout + "|${stacktrace}";
_nLogLoggingConfiguration.AddTarget(CONSOLE_WITH_STACK_TRACE, consoleTargetWithStackTrace);
var consoleTargetWithoutStackTrace = new ConsoleTarget();
consoleTargetWithoutStackTrace.Name = CONSOLE_WITHOUT_STACK_TRACE;
consoleTargetWithoutStackTrace.Layout = _loggerModel.layout;
_nLogLoggingConfiguration.AddTarget(CONSOLE_WITHOUT_STACK_TRACE, consoleTargetWithoutStackTrace);
}
问题是我不确定如何测试它。我有我的主密码。
public class ConsoleTargetBuilderUnitTests
{
public static IEnumerable<object[]> ConsoleTargetBuilderTestData
{
get
{
return new[]
{
new object[]
{
new LoggerModel(),
new LoggingConfiguration(),
2
}
};
}
}
[Theory]
[MemberData("ConsoleTargetBuilderTestData")]
public void ConsoleTargetBuilder_Should_Add_A_Console_Target(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration, int expectedConsoleTargetCount)
{
// ARRANGE
var targetBuilderMock = new Mock<ITargetBuilder>();
targetBuilderMock.Setup(x => x.AddNLogConfigurationTypeTagret()).Verifiable();
// ACT
var consoleTargetBuilder = new ConsoleTargetBuilder(loggerModel, nLogLoggingConfiguration);
// ASSERT
Assert.Equal(expectedConsoleTargetCount, nLogLoggingConfiguration.AllTargets.Count);
}
请指引我正确的方向。
【问题讨论】:
-
最简单的方法是将 ConsoleTarget 类注入到方法中。然后你可以在模拟上设置期望。更熟悉 Moq 框架的人可以帮助您编写代码
-
你在你想测试的类的接口上创建一个模拟。为什么 ?然后您正在实例化 ConsoleTargetBuilder 但构造函数中没有方法调用。你在测试什么?你的模拟永远不会被调用。
-
您是要测试 AddNLogConfigurationTypeTagret 内的代码还是只是调用 AddNLogConfigurationTypeTagret 的事实?
-
@sleepwalker,我想要两件事。 A) 方法被调用。 B) 添加了两个目标。所以预期的计数是 2。
-
没有人会调用那个方法。得自己调用,或者改构造函数调用AddNLogConfigurationTypeTagret();
标签: c# unit-testing moq xunit