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 function 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);
Related
Some tests are used with this annotation #RunWith(Theories.class) in JUnit and I don't know when and why we use it?
You should use them when you would like your tests to focus on the generalized relationship between inputs and outputs. See: https://blogs.oracle.com/jacobc/entry/junit_theories.
I think capturing multiple types of input are one thing. The high level idea is that you want to test if your method is true for all possible inputs.
For example, let's say I have some complex business process that takes 5 different inputs, and let's say for each input, there's 10 possible states, so we end up with 10*10*10*10*10 = 100,000 possible input states, which means we need to know beforehand what all these 100,000 output values are.
However, you probably realize that you don't need to actually enumerate all 100,000 states. There's probably a subset that you are interested in. Let's theorize for example:
"Admins have no permission restriction". And if I wanted to assert that this is true, my Test ends up looking like the pseudo-code below.
#Test
public void AdminsHaveNoPermissionRestriction(User user, BusinessProcess bp, Input a, Input b ...) {
Assume.assumeThat("User is an admin", user.hasRole(admin);
// .. rest of test which uses bp, a, b etc...
)
The nice thing is that we skip un-interested objects (non-admins) because it fails the assumptions.
I am not looking for the answer to this question but just a brief outline of how to do it. This is a question from a exam past paper.
It states: Describe in English a sequence of tests that you might use to test code to implement the NumberCoversion class. Your tests should cover all the conditions described in the above definition.
I won't write the specification of the class but it contains things like: it must take String as input and output, accepting two parameters and returning null if a number is not valid etc.
The question is worth 10% so will I just be required to write a series of things like: Ensure that the constructor only accepts two parameters of type int, and not anything else e.g. double or accept 3 parameters.
Would it be worth writing possible JUnit test methods in English/Pseudocode.
Would this be the right sort of thing to write for tests in English?
I think the goal is to describe a test case which checks each of the specifications in the question, whilst also avoiding attempting to test things which are limited by the language construct (e.g. wrong number/type of arguments).
Describe in English what you will do if you write tests. Typically it's usage of the NumberConversion class.
According to the question, you need to describe tests in English. I think that jumping to JUnit unit tests is more than being asked for. If I answered this question, I would start by looking at the definition given of the NumberConversion class. I would describe tests that use valid inputs as well as tests that use invalid ones. For each test describe how you will ensure that the NumberConversion class behaves as expected, including expected error conditions.
As an example for what might be appropriate...
If the specifications were:
Takes a string as input
The string can be an arbitrarily large non-negative integer
If the string is not a non-negative integer, an exception is thrown
Then I would probably answer something along the lines of:
I would test with "42" as input to check that the method works with a "normal" number
I would test with "0" as input to check that the method works with the edge case number
I would test with "9223372036854775808" (1 more than Long.MAX_VALUE) as input to check that the method works with a number larger than the fixed length integers provided by Java
I would test with "-1" as input and ensure that an exception is thrown, as negative input is invalid
I would test witht "0xa" as input and ensure that an exception is thrown, as hexadecimal input is invalid
I would test witht "0.1" as input and ensure that an exception is thrown, as non integral input is invalid
I'm being asked to sketch a Junit test case for a method:
public int checkOutItems(ArrayList<int> trolley)
which will return an ArrayList of item name and price list.
It is also defined the types of test case like normal condition,boundary, and exceptional.
I'm just wondering what is meant by boundary and exceptional?
Normal will just be to compare the input and output but boundary and exceptional?
Boundary tests
Let's say you need to test something that adds up to 50 numbers together. Your first boundary test would be to pass a list containing no items, the lower boundary. Your next test would be to pass a list that contains 50 numbers, the upper boundary. Boundary tests are often easy to write as you try to test the maximum or minimum (or a combination of them) parameter values. These should all work, of course, otherwise they belong in the next section.
Exception tests
What will happen if you pass a null list to a method? What happens if your list contains 51 items instead of the 50 maximum? What about passing in a list of Strings instead of Integers, for example? Exception tests are designed to try and break the program, either to test known limitations, or to test exception handling.
Boundary test - pass boundary valid arguments (like pass empty array to length function and check that result is zero)
Exceptional test - pass invalid argument and check that appropriate exception is raised.
I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.
However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.
So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?
Using the Hamcrest CoreMatcher (included in JUnit 4.4 and later) and assertThat():
assertThat(myString, anyOf(is("value1"), is("value2")));
I would use AssertJ for this:
import static org.assertj.core.api.Assertions.*;
assertThat("hello").isIn("hello", "world");
It's more concise and it will give you a descriptive message when the assertion fails.
I am using the following, I hope this would help:
String expectedTitles[] = {"Expected1","Expected2"};
List<String> expectedTitlesList = Arrays.asList(expectedTitles);
assertTrue(expectedTitlesList.contains((actualTitle)));
You can use Hamcrest for this:
assertThat(testString, anyOf(
containsString("My first string"),
containsString("My other string")));
(I see Joachim just answered very similarly (+1)... i'll add this as another example.)
I read all answers, but the one that seems most compact and expressive to me is using Hamcrest's isOneOf which is already included in JUnit
assertThat(result, isOneOf("value1", "value2"));
which gives you a nice error message when failing.
java.lang.AssertionError:
Expected: one of {"value1", "value2"}
but: was "value"
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
[...]
If your using junit I'd just do something like the following:
assertTrue(myString.equals("Value1") || myString.equals("Value"));
Consider writing a custom hamcrest matcher returned by a method, in this case containsOneOf, i.e.:
assertThat(myString, containsOneOf("value1", "value2"));
In keeping with the "xUnit patterns" you should avoid conditional logic in your matcher, a loop with a break statement should suffice.
Have a look at Hamcrest and xUnit Patterns for more information.
If the content for a line is fixed you can split it at line endings before comparing. Then simply compare each line to a set of expected values.
Something like this:
Set<String> expectedValues = ...
String[] split = text.split("\n");
for(String str : split) {
assert(expectedValues.contains(str));
}
If you want to check that all expected values are present you can assert that expectedValue.remove(str) == true and assert after the loop that the Set is empty. If some lines may occur multiple times you have to use a Bag instead of a Set.
The simplest/most efficient might be
assert str.equals(result1) || str.equals(result2);
This will effectively have no overhead when you don't have assertions turned on.
Assuming the method under test returns an array, you could test using Hamcrest's arrayContainingInAnyOrder.
assertThat(result, is(arrayContainingInAnyOrder("value1", "value2", "value")))
Note: use of is wrapper is purely optional, used only as readability sugar.
I think you can just use assertTrue:
assertTrue(testString.matches("string1|string2"));
Simple solution using AssertTrue. Just create a List.of() the expected values and check is it contains the expected value.
assertTrue(List.of("expected_1", "expected_2").contains("actual))
If you do not have or can't use third-party libraries except junit core, you can use this small helper method:
public static void assertListContains(List<Object> expected, Object actual) {
if (!expected.contains(actual)) {
fail("Expected: " + expected + " Actual: " + actual);
}
}
Advantage, in contrast to other workaround answers, is that you can see what was expected and what was actual:
org.opentest4j.AssertionFailedError: Expected: [1, 2] Actual: 3
It's an old post, but I wanted to have an native easy answer, without having extra libraries to add. :)
So I did :
String e
e = "ear"
j = "jars"
assert (j == "jar" || e == "ear")
or if you want them to be both true
assert (j == "jar" && e == "ear")
This seems to me like the simplest solution ...
assert obtainedValue in [acceptedValue1, acceptedValue2]
I want to create a program for generating the series for the given base-n. ,
for example if my input is 2,then series shuould be, 00,01,10,11,etc.,(binary)
if my input is 10,then series shuould be,1,2,3,4,5,etc.,(decimal)
is there any general mechanism to find these numbers so that I can program for base-n.,
UPDATE:-
After,working out.,i face issue.
If I want to process that integer how to do that? Some body commented that, BaseInteger class I should use. please elaborate
You could use Integer's toString(int i, int radix) method for that.
For example:
Integer.toString(2, 2) // number 2, base 2
returns the string:
"10"
Note that the radix should be between 1 and 36.
You might be looking for something like this (take a peek at "Algorithm: Constructing Base b
Expansions"):
https://docs.google.com/viewer?url=http://websupport1.citytech.cuny.edu/faculty/dkahrobaei/Integers%2520and%2520Algorithms.pdf
I think you should first figure in which format you need the results. If they should be Strings, Bart's answer would probably suit you. An integer representation, which does actually mean something else (e.g. the int 10 does mean 2 with base 2) seems awkward to me. If i would need something like you described, i would probably implement a BaseNumber class first.