1
votes

I have a Prism dialogService for confirmation (Yes and No buttons in dialog), and I use it this way;

bool confirmed = false;

DialogParameters p = new DialogParameters
{
    { "title", title },
    { "message", message }
};
dialogService.ShowDialog("ConfirmationDialog", p, r => { confirmed = r.Result == ButtonResult.OK; });

if (!confirmed)
{
    return;
}

// code I am not able to test

It works like a charm, but I am not able to test the code after the return, because "confirmed" is always false while I am executing tests, so it always returns and the code after the "return" is never executed.

I think the best way to test it should be to inject somehow the IDialogResult value in "r", so I can force that always I am testing r.Result == ButtonResult.OK. But... how can I do that?

Maybe my approach for confirmation dialog is not good, or maybe I am missing something, so any suggestion would be a great help for me.

Note: I use Fake It Easy for testing, but it is not a problem is the solution in explained in any other testing framework.

UPDATE: this is the implementation of the dialogService in the test:

dialogService = A.Fake<IDialogService>();

And then it is injected in the ViewModel:

var viewModel = new MyViewModel(dialogService);

Thank you

1
It would help to see the implementation/creation of the dialogService in your test. If it's a mock, you could tell it to pass to the callback any arguments you desire... - Haukinger
@Haukinger, you are right, I have updated the question including how dialogService is implemented. Thank you - Carlos

1 Answers

2
votes

I don't know Fake It Easy, but with MOQ and NUnit, I'd write something like this:

// Arrange
var dialogServiceMock = new Mock<IDialogService>();
dialogServiceMock.Setup( x => x.ShowDialog( It.IsAny<string>(), It.IsAny<IDialogParameters>(), It.IsAny<Action<IDialogResult>>() ) )
                 .Callback<string, IDialogParameters, Action<IDialogResult>>( ( n, p, c ) => c( new DialogResult( ButtonResult.OK ) ) );

// Act
var receivedResult = ButtonResult.None;
dialogServiceMock.Object.ShowDialog( "my name", new DialogParameters( "my parameters" ), r => receivedResult = r.Result );

// Assert
Assert.That( receivedResult, Is.EqualTo( ButtonResult.OK ) );

Key point is the setup of the callback. Without it, the mock has no idea what to do with the Action<IDialogResult> parameter and even if it wanted to call it, it wouldn't know the parameters to use.

EDIT: Fake It Easy's equivalent to MOQ's Callback seems to be Invokes (found here).