c# - "Simulate"单元测试中的命令行参数

标签 c# unit-testing

我有一些功能,这取决于命令行参数,不同的参数应该导致不同的结果。

我不能直接“模拟”这个参数,因为有某种链依赖关系 - 我需要对一些 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/

相关文章:

unit-testing - 你如何说服别人编写单元测试?

c# - 从 DateTime 月份和日期(字符串)中删除 '0'(数字)

c# - 局部函数中声明的值类型变量是否是堆栈分配的?

c# - 将 DisplayFor 与嵌套属性的单个索引一起使用 - Lambda 参数不在范围内

c# - 隐式运行单元测试

java - JUnit 测试,无根测试 : initializationError

c# - C#中的网页爬取

c# - 从 WebMethod 返回对象 (AJAX ASP.net)

java - JUnit 测试用例使用 Mockito : null pointer exception

angularjs - 在 angularjs 中进行单元测试时如何模拟 $location