使用来自外部文件的数据进行 xUnit 测试 [英] xUnit test using data coming from external file

查看:33
本文介绍了使用来自外部文件的数据进行 xUnit 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我试图了解 xUnit 测试的工作原理,特别是,我发现有 3 种方法可以将数据作为参数传递以测试类方法(InlineData、ClassData 和 MemberData).但这是我的问题:有没有机会从外部文件中获取这些数据?(例如一个 Json 文件)我无法找到有关此主题的足够材料,感谢您的关注!

In these days I'm trying to understand how xUnit tests work and, in particular, I discovered that there are 3 ways to pass data as parameters in order to test class methods (InlineData, ClassData and MemberData). But here Is my issue: is there any chance to get these data from an external file? (For example a Json file) I wasn't unable to find enough material about this topic, thanks for the attention!

推荐答案

我相信最简洁的方法是使用 ClassData 来实现这一点,这样你就可以从任何你喜欢的地方为你的测试填充数据.考虑一下:

I believe the cleanest way is using ClassData for that so that you can populate data for your test from wherever you like. Consider this:

public class TestData : IEnumerable<object[]> 
{
    private IEnumerable<object[]> ReadFile() 
    {
        //read your file
    }

    public IEnumerator<object[]> GetEnumerator() 
    {
        var items = ReadFile();
        return items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

当然,您可以在 测试的排列阶段,然后在数据上循环测试方法.但在这种情况下,您将失去检测所有失败测试而不仅仅是第一个的优势.

Of course, you could just populate data from a file during the Arrange phase of your test and then just loop your test method over the data. But in that case, you would lose the advantage of detecting all failing tests instead of just the first.

这篇关于使用来自外部文件的数据进行 xUnit 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆