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. For example, if the functio开发者_如何学JAVAn is called with the integer number 3 then the returned string should be '11'.
Write a sequence of test specifications in English possibly using the "given", "when", and "then" sequence and their equivalent JUnit code.
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.
@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:
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. There is assertNotEquals, that's probably what you're looking for.
In your code sample, when you write 'assertEquals(3, 11);' You assert that 3 equals 11 (base ten) which will always be 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".
you can add testcases for zero and negative numbers..
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);
精彩评论