简体   繁体   English

Junit测试依赖方法

[英]Junit testing dependent methods

I'm having trouble with Junit testing, and can find little info online. 我在使用Junit测试时遇到了麻烦,可以在网上找到很少的信息。

Firstly, I want to test 2 methods, 首先,我想测试2种方法,

1. setTable(int r, int c, String s) 1. setTable(int r, int c, String s)

2. getTableString() . 2. getTableString()

I managed to test the first one, but the second one requires that the table be already built (the table being a private static char[][] with a getter, and is built by the first method). 我设法测试第一个,但第二个要求已经构建了表(该表是带有getter的private static char[][] ,并且由第一个方法构建)。

How do I go about testing this second method? 我该如何测试第二种方法? I thought of doing this: 我想过这样做:

    public void testGetTableString() {

        MyClass test = new MyClass();
        test.setTable(5, 4, "string");
        String toTest = test.getTableString();
        assertEquals("expected result", toTest);
    }

This however doesn't seem right since it's dependent on setTable working. 然而,这似乎并不正确,因为它依赖于setTable工作。

I also thought of initializing test.setTable(5,4,"string") in the setUp() method, but that would mean that I'd have to change the parameters for setTable in the setUp() method each time and not be able to track my tests; 我还想过在setUp()方法中初始化test.setTable(5,4,"string") ,但这意味着我每次都必须在setUp()方法中更改setTable的参数而不是能够跟踪我的测试; plus it would setUp() for my first method too, which I don't want. 加上它也会为我的第一个方法setUp() ,我不想要。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

RE: This however doesn't seem right since it's dependent on setTable working. RE: 然而这似乎不对,因为它依赖于setTable工作。

What you have done is perfectly appropriate. 你所做的是完全合适的。 If getTableString() is the method-under-test, then the best way to isolate it is to setup the necessary pre-conditions. 如果getTableString()是被测方法,那么隔离它的最佳方法是设置必要的前置条件。 Also, by putting the setTable call right in this test method, you have isolated these conditions to this one test (as opposed to putting the call in setup() which will be seen by all test methods). 此外,通过将setTable调用置于此测试方法中,您已将这些条件隔离到此一个测试(而不是将调用置于setup()中,这将被所有测试方法看到)。

Just because you have two methods (to test) doesn't mean there has to be two methods to test them. 仅仅因为你有两种方法(测试)并不意味着必须有两种方法来测试它们。 You can club that in a single junit test. 你可以在一次junit测试中加入。

Since they are related, you cant really say setXY works unless you verify with getXY 既然它们是相关的,你就不能说setXY有效,除非你用getXY验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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