单元测试wpf(禁用消息框)

SAT*_*SAT 1 c# wpf unit-testing

我正在为我的代码编写单元测试.并使用'Microsoft.VisualStudio.TestTools'.对于包含消息框的函数,我不想在运行"单元测试"时弹出消息.我可以通过使用以下代码来做到这一点,

 public static class UnitTestDetector
{
    static UnitTestDetector()
    {
        string testAssemblyName = "Microsoft.VisualStudio.QualityTools.UnitTestFramework";
        UnitTestDetector.IsInUnitTest = AppDomain.CurrentDomain.GetAssemblies()
            .Any(a => a.FullName.StartsWith(testAssemblyName));
    }

    public static bool IsInUnitTest { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

但是对于这个解决方案,我必须在实际函数中使用'IsInUnitTest'来禁用消息框.还有其他解决方案吗?

Fab*_*bio 5

是.

创建显示消息的界面

public interface IDisplay
{
    void ShowMessage(string message);
}
Run Code Online (Sandbox Code Playgroud)

例如,通过构造函数将接口传递给您正在测试的类

public class ViewModel
{
    private readonly IDisplay _display;

    public ViewModel(IDisplay display)
    {
        _display = display;
    }

    public void DoSomething()
    {
        // do something
        _display.ShowMessage("result of do something");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在测试中,您将通过测试的实现

public class FakeDisplay : IDisplay
{
    public string LastDisplayedMessage => _lastDisplayedMessage;

    public void ShowMessage(string message)
    {
        _lastDisplayedMessage = message;
    }
}

[Test]
public void WhenDoSomething_ShouldShowMessage()
{
    var fakeDisplay = new FakeDisplay();
    var viewmodel = new ViewModel(fakeDisplay);

    viewmodel.DoSomething();

    fakeDisplay.LastDisplayedMessage.Should().Be("result of do something");     
}
Run Code Online (Sandbox Code Playgroud)

在实际的生产代码中,您将实现将显示消息并将其传递给viewmodel的接口.

public class Display : IDisplay
{         
    public void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }
}   
Run Code Online (Sandbox Code Playgroud)