在测试之间传递JUnit数据 [英] Passing JUnit data between tests

查看:111
本文介绍了在测试之间传递JUnit数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现在创建一些CRUD测试时,你不能在一个测试中设置数据并让它在另一个测试中读取(数据在每次测试之间设置回初始化)。

I just discovered when creating some CRUD tests that you can't set data in one test and have it read in another test (data is set back to its initialization between each test).

我所要做的就是(C)用一次测试重新创建一个对象,然后用(R)用另一个测试重新创建一个对象。 JUnit是否有办法做到这一点,或者它是否在意识形态上编码,以便不允许测试相互依赖?

All I'm trying to do is (C)reate an object with one test, and (R)ead it with the next. Does JUnit have a way to do this, or is it ideologically coded such that tests are not allowed to depend on each other?

推荐答案

那么,对于单元测试,你的目标应该是测试最小的孤立的代码片段,通常是按方法测试。
所以 testCreate()是一个测试用例而 testRead()是另一个。但是,没有什么可以阻止您创建 testCreateAndRead()来一起测试这两个函数。但是如果测试失败,那么测试失败的代码单元是什么?你不知道。那些测试更像集成测试,应该区别对待。

Well, for unit tests your aim should be to test the smallest isolated piece of code, usually method by method. So testCreate() is a test case and testRead() is another. However, there is nothing that stops you from creating a testCreateAndRead() to test the two functions together. But then if the test fails, which code unit does the test fail at? You don't know. Those kind of tests are more like integration test, which should be treated differently.

如果你真的想这样做,可以创建一个静态类变量来存储对象由 testCreate()创建,然后在 testRead()中使用它。

If you really want to do it, you can create a static class variable to store the object created by testCreate(), then use it in testRead().

由于我不知道你在谈论什么版本的Junit,我只拿起古老的Junit 3.8:

As I have no idea what version of Junit you talking about, I just pick up the ancient one Junit 3.8:

非常难看但是有效:

public class Test extends TestCase{

    static String stuff;

    public void testCreate(){
        stuff = "abc";
    }

    public void testRead(){
        assertEquals(stuff, "abc");
    }
}

这篇关于在测试之间传递JUnit数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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