I am unit testing view models and am using mbunit with moq to mock the private method od the class but my requirement is to verify in the assertion part of the test that a some another method is called (which is a dialog box ) present inside the Method which is Under Unit test.

有帮助吗?

解决方案

You can easily check a method being called with Moq using the following code:

[TestFixture]
public class UnitTest1
{
    [Test]
    public void TestMethod1()
    {
        // Create a mock of your interface and make the methods verifiable.
        var mock = new Mock<ISomeDependency>();
        mock.Setup(m => m.DoSomething())
            .Verifiable();

        // Setup your class which you expect to be calling the verifiable method
        var classToTest = new SomeClass(mock.Object);
        classToTest.DoWork();

        // Verify the method is called
        mock.Verify(m => m.DoSomething());
    }
}



public class SomeClass
{
    private readonly ISomeDependency _someDependency;

    public SomeClass(ISomeDependency someDependency)
    {
        _someDependency = someDependency;
    }

    public void DoWork()
    {
        _someDependency.DoSomething();
    }
}

public interface ISomeDependency
{
    void DoSomething();
}

public class SomeDependency : ISomeDependency
{
    public void DoSomething()
    {

    }
}

Basicly all you are looking for is the Verifiable in the Arrange part of ur unit test, and the Verify in the Assert part.

其他提示

When something is hard to unit test, that's a "code smell" that you have a design issue.

In this case, the fundamental issue is that you're trying to perform a UI action within your viewmodel. That's bad.

The approach I take when I'm doing MVVM is to raise an event in my viewmodel, e.g. ConfirmationRequired. Then in the view, I hook an event handler up to the event. The event handler in my view is what's responsible for actually displaying the message box.

This is dead simple to unit test. This example is in MSTest, but MBUnit is more or less equivalent.

[TestMethod]
public void User_Confirmation_Is_Requested()
{
    var mre = new ManualResetEvent(false);
    var vm = MyApplicationViewModel();
    ConfirmationRequestedEventArgs actual = null;
    vm.ConfirmationRequired += (sender, args) => {
    {
            actual = args;
            mre.Set();
    };

    vm.DoSomethingThatRequiresConfirmation();
    if (!mre.WaitOne(1000))
    {
        Assert.Fail("The event was never received.");
    }
    Assert.AreEqual("Whatever", actual.SomeProperty ?? string.Empty);
}

The great thing here is that you can even simulate user responses -- let's say your ConfirmationRequestedEventArgs has a property called UserResponse. You can set UserResponse in the event handler of your unit test and then make sure that when the user clicks the "Cancel" button, some other state in the viewmodel changes accordingly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top