创建模拟数据以进行单元测试 [英] Creating mock data for unit testing

查看:112
本文介绍了创建模拟数据以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为自己在TDD领域还很陌生.但是发现无论我使用哪种方法(模拟框架或存根我自己的对象),我都会发现必须编写大量代码来创建模拟数据.我喜欢加载对象以创建内存数据库的想法.但是我不喜欢的是用大量代码使测试混乱,其唯一目的是创建模拟数据.在数据需要考虑所有不同情况的情况下尤其如此.

I consider myself still pretty new to the TDD scene. But find that no matter which method I use (mock framework or stubbing my own objects) I find that I have to write a lot of code to create mock data. I like the idea of loading up objects to create an in-memory database. But what I don't like is cluttering up my tests with a ton of code for the sole purpose of creating mock data. This is especially the case when the data needs to account for all the different cases.

我希望获得一些建议,以获得更好的方法.

I'd love some suggestions for a better way of doing this.

在我看来,我应该能够从某个数据存储中一次将数据加载到已知状态,然后我可以使用该状态的快照,该快照已在每种测试方法使用之前加载到测试设置/初始化中被执行.这将满足适当的测试实践,同时提供便利,让我专注于编写测试,而不是编写代码来手动"创建测试数据.

It would seem to me that I should be able to load the data once into a known state from some data store and then I could use a snapshot of that state which is loaded in the test setup/initialize before each test method is executed. This would satisfy proper testing practices while providing convenience and let me focus on writing tests instead of writing code to create test data "by hand".

推荐答案

也许您可以尝试使用NBuilder库.它提供了非常流畅的界面,并且易于使用.您可以将其用于生成具有默认值的类的单个实例,或生成具有默认值或替代值的列表.您可以查看一个.

May be you could try the NBuilder library. It provides a very fluent interface and is easy to use. You can use it for generating single instances of a class with defualt values or generate lists with default or overriden values. You can have a look at this one.

这篇关于创建模拟数据以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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