简体   繁体   中英

How to unit test a prompt validator in Bot Framework V4

In my dialog I use a validator to check the users input. I have a line that looks like this:

AddDialog(new TextPrompt(nameof(AskForCustomerId), validators.TestValidator));

I also have a class which contains my validations for this dialog. The class looks like this:

public class MyValidator : IMyValidator
{
    public async Task<bool> TestValidator(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
    {
        // Do some validations...
        
        return true;
    }
}

I thought that it's a good idea to have my validation code separated in another class.

But now I'd like to write unit tests for this particular class. But how can I do this?

I tried the following, but I can't create an instance of PromptValidatorContext , because the constructor is internal...

[Fact]
public void Test()
{
    // Arrange
    var sut = new MyValidator(sessionManagerMock.Object);
    var prompt = new PromptValidatorContext(); // ctor is internal.. cant create instance.

    // Act
    sut.TestValidator( ) // How to pass params?

    // Assert
}

Anyone any idea how to unit test this?


Update

So I have a Dialog in which I inject my "Validator" class. My Dialog class looks like this:

public class MyDialog : BaseDialog
{

    public MyDialog(ICustomerValidator validator) : ComponentDialog
    {
        AddDialog(new WaterfallDialog(nameof(WaterfallDialog),
            new WaterfallStep[]
            {
                // ... my steps
            }));

        AddDialog(new TextPrompt(nameof(Step1Example)));
        AddDialog(new TextPrompt(nameof(Step2Example), validator.CustomerIdValidator));
        // etc.

        InitialDialogId = nameof(WaterfallDialog);
    }
}

I the code for validation in a separate class (hence the ICustomerValidator )

public class CustomerValidator : ICustomerValidator
{
    public async Task<bool> CustomerIdValidator(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
    {
        // example
        return promptContext.Context.Activity.Text == "100";
    }
}

This all works fine. But how do I write a unit test solely for the CustomerValidator class?

Prompt validators are not meant to be called directly, even in tests. They are meant to be tested indirectly using test flow as seen in PromptValidatorContextTests , or by using a dialog test client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM