简体   繁体   English

Java JUnit测试

[英]Java JUnit Testing

Chris has written a function called toBinary that has an input parameter of an integer number and returns a string that represents the binary equivalent. 克里斯编写了一个名为toBinary的函数,该函数具有一个整数的输入参数,并返回一个表示二进制等效项的字符串。 For example, if the function is called with the integer number 3 then the returned string should be '11'. 例如,如果函数使用整数3调用,则返回的字符串应为'11'。

Write a sequence of test specifications in English possibly using the "given", "when", and "then" sequence and their equivalent JUnit code. 用英语写一个测试规范序列,可能使用“给定”,“何时”和“那么”序列及其等效的JUnit代码。

My answer is: 我的答案是:

The test should cover normal cases, extreme cases, and erroneous cases. 该测试应涵盖正常情况,极端情况和错误情况。 Given an integer for example 3, it should then covert it to 11 after the method is executed. 给定一个整数(例如3),则在执行该方法后应将其隐藏为11。

@Test
public void testToBinary() {
Binary aBinary = new Binary();
assertEquals(3, 11);
assertEquals(2, 10);
assertFail(10, 8575);
}

is this correct? 这个对吗?

Those asserts don't make sense -- of course, 3 != 11. You'd need apply the conversion method to the input and verify that the output is expected: 这些断言没有意义-当然是3!=11。您需要将转换方法应用于输入并验证是否期望输出:

assertEquals("11", aBinary.someConvertMethod(3));

The expected value must be the first parameter, and the actual value is the second parameter. 期望值必须是第一个参数,而实际值是第二个参数。

Also, assertFail isn't a real method. 另外,assertFail也不是真正的方法。 There is assertNotEquals, that's probably what you're looking for. 有assertNotEquals,这可能就是您想要的。

In your code sample, when you write 'assertEquals(3, 11);' 在代码示例中,当您编写“ assertEquals(3,11);”时 You assert that 3 equals 11 (base ten) which will always be false. 您断言3等于11(以10为底),它将始终为false。

Would you not require something like 你会不需要像

assertEquals("11", toBinary(3));

Which tests that your function, given an input of three, returns the String "11". 在给定三个输入的情况下,该函数测试您的函数是否返回字符串“ 11”。

您可以为零和负数添加测试用例。

First and foremost each unit test should have at most one assert. 首先,每个单元测试最多应有一个断言。 As others have stated you must invoke the constructor or whichever method you are relying on in the actual test case: 正如其他人所述,您必须在实际测试用例中调用构造函数或所依赖的任何方法:
assertEquals("11",toBinary(3);

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

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