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

查看:17
本文介绍了在测试之间传递 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天全站免登陆