我有一些功能,这取决于命令行参数,不同的参数应该导致不同的结果。
我不能直接“模拟”这个参数,因为有某种链依赖关系 - 我需要对一些 xaml 控件进行单元测试,它依赖于 View 模型,它依赖于某些附加类,它使用获取命令行参数Environment.GetCommandLineArgs
,我不能直接影响最后一个类来手动设置参数而不是使用 GetCommandLineArgs
.
所以,我想知道,有没有办法让Environment.GetCommandLineArgs
返回值我希望它返回,对于某些单元测试。
最佳答案
您需要抽象Environment.GetCommandLineArgs
或者什么东西最终在你可以 mock 的东西背后调用它
public interface ICommandLineInterface {
string[] GetCommandLineArgs();
}
最终可以在一个具体的类中实现
public class CommandInterface : ICommandLineInterface {
public string[] GetCommandLineArgs() {
return Environment.GetCommandLineArgs();
}
}
并且可以使用
Moq
进行测试和 FluentAssertions
[TestMethod]
public void Test_Should_Simulate_Command_Line_Argument() {
// Arrange
string[] expectedArgs = new[] { "Hello", "World", "Fake", "Args" };
var mockedCLI = new Mock<ICommandLineInterface>();
mockedCLI.Setup(m => m.GetCommandLineArgs()).Returns(expectedArgs);
var target = mockedCLI.Object;
// Act
var args = target.GetCommandLineArgs();
// Assert
args.Should().NotBeNull();
args.Should().ContainInOrder(expectedArgs);
}
关于c# - "Simulate"单元测试中的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36626668/