Check if-else statement in one time using JUnit testing - java

I try to test on how to get index 0 and 5 value from my file. I can get the value. But, to test the value with JUnit, i can only test if(index==0) but it did not check for (index==5).
So, how can i test both index in one time using if else ?
#Test
public void test(){
for(index = 0; index<arrayList.size(); index++){
if(index==0 && index==5){
given()
.header(something)
.get(something)
.then(something)
.body("try", contains(arrayList.get(index).getSomething(),arrayList.get(index).getSomething()))
.log().all()
.statusCode(HttpStatus.SC_OK)
}
}
}

In a unit test each test method verifies a single expectation about the tested units behavior.
Therefore you write different tests for different input and/or different expectations.
Also tests should not have (self written) logic.
If you need to iterate over input values you might consider Parameterized tests: http://blog.schauderhaft.de/2012/12/16/writing-parameterized-tests-with-junit-rules/

Simple:
for(index = 0; index<arrayList.size(); index++){
if(index==0 && index==5){
This says: if index is 0 and index is 5.
An int can't have two values at the same time. You probably want:
if(index==0 || index==5){
But of course: Timothy is correct, you want one "check" per test.
The proper solution would be: write a private helper method that takes an parameter indexToCheckFor, so that you can do
private void testForIndex(int indexToCheckFor) {
....
if(index == indexToCheckFor) {
and then have two #Test methods, one calling testForIndex(0), the other one calling for 5.

Related

Write if else condition based on test execution order in TestNG

I am trying to execute a code in which I am stuck and landed in a question whether we can write an if else condition in java with respect to the execution order or priority number in TestNG.
What I wanted to do is,
if(TestNGprioritynum==1){
HSSFSheet s = newsheet(sheetnum);
}
if(TestNGprioritynum==2){
HSSFSheet s = newsheet(sheetnum1);
}
TestNGprioritynum is not a class or any code. It is just an illustration of what I want to do. Is there any library inside TestNG or any third party tool or anything in Java which I can use to decide actions on condition with respect to priority of TestNG test cases? Any possible way to do this?
You can get the priority of the test method being run using the ITestResult object in a method annotated with #BeforeMethod. Then depending on the priority, set an attribute which could be used in the actual test method.
#BeforeMethod
public void beforeMethod(ITestContext ctx, ITestResult res) {
ITestNGMethod method = res.getMethod();
int num = (method.getPriority() == 1) ? sheetNum : sheetNum1;
ctx.setAttribute("sheetnum", num);
}
#Test(priority = 1) {
public void yourTest(ITestContext ctx) {
HSSFSheet s = newsheet((int) ctx.getAttribute("sheetnum");
}

Does not contain 4 grade - Java

public class Degree {
public Degree(List<Grade> year2, List<Grade> year3) {
if (year2.size() != 4 || year3.size() != 4) {
throw new IllegalArgumentException();
}
}
i have statement for "does not contain 4 grade" to create Junit test. is there a better way to improve this statement (for my knowledge to help me out in future).
#Test(expected = IllegalArgumentException.class)
public void donotcontaingrade() {
List<Grade> year2 = new ArrayList<>();
year2.add(new Grade(1));
year2.add(new Grade(2));
year2.add(new Grade(3));
List<Grade> year3 = new ArrayList<>();
year3.add(new Grade(1));
year3.add(new Grade(2));
year3.add(new Grade(3));
new Degree(year2, year3);
}
Example of my Junit test
Your test would pass, in that the exception would be thrown.
However, you made a common mistake of trying to test multiple issues in one test. You really need four tests for full coverage.
The Happy Path, where your pass in two valid arguments and get back an instance, not an exception.
You pass a bad value and a good value, and get an exception.
You pass a good value and a bad value, and get an exception.
You pass in two bad values and get an exception.
Late addition: When an if statement contains an OR operator, then you can't get 100% coverage in tools. That's because the coverage tool wants to check both conditions false. However, the OR stops checking on the first false, so the second condition is not checked.
To 100% coverage, split the if with OR into two if. The code execution is the same, but the coverage tool will see all code exercised.

How to return an array in java? Using Eclipse

Heres what I have for the method:
public int[] generateNumbers(int numberOfTimes){
int[] generatedNumbers = new int[numberOfTimes];
int counter = 0;
while(counter < generatedNumbers.length){
generatedNumbers[counter] = generator.nextInt(this.maxNumber - this.minNumber + 1) + this.minNumber;
counter++;
}
return generatedNumbers;
}
I created a JUnit4 Test, and just to test its output, I have this:
#Test
public void testGenerateNumbers() {
assertEquals(this.simulator.generateNumbers(1), 2);
}
Now, this returns false obviously, and the expected value was <[I#6f1d0b1>. Why am I getting a location instead of the actual array? Any help would be appreciated... By the way, we must use assertEquals, so anything else is out of the question, and yes I realize using something else to test this is easier.
You need to use assertArrayEquals()
assertArrayEquals(this.simulator.generateNumbers(1), new int[] {2});
Why am I getting a location instead of the actual array?
You're getting the array (reference), but the error message is printing out the result of calling toString() on it. That's not terrible useful to you, unfortunately.
If you're actually trying to check the length, you need to do that:
assertEquals(1, simulator.generateNumbers(1).length);
Or to check the first value within the array:
assertEquals(2, simulator.generateNumbers(1)[0]);
(Note that the expected value comes first. It's really important to get the "expected" and "actual" order right in order to make the error messages sensible.)
Of course assertArrayEquals is the best approach here, but if you really need to use assertEquals, you could convert the array to a list:
assertEquals(Arrays.asList(new int[] { 2 }),
Arrays.asList(simulator.generateNumbers(1)));
(It's not clear why assertEquals would be the only kind of assertion available to you... that's a very odd constraint.)
If you absolutely must use assertEquals (I'd like to know why), you can do this:
assertEquals(true, Arrays.equals(new int[] { 2 }, this.simulator.generateNumbers(1)));

I fail junit tests because of return type (I think)

So I have a class full of junit tests and a class full of methods that perform binary operations. The tests are checking to see if I have the right values at certain points.
I am failing a lot of tests because of what I believe to be is the return type. For example I get the message
junit.framework.ComparisonFailure: null expected:<[000]> but was <[BinaryNumber#4896b555]>
If I'm understanding this it's saying that it was looking for an array containing 000 but it got a BinaryNumber (which is the required return type). To help clarify here is one of the methods.
public BinaryADT and(BinaryADT y) {
int[] homeArr = pad(((BinaryNumber) y).getNumber());
int[] awayArr = ((BinaryNumber) y).pad(getNumber());
int[] solution = new int[awayArr.length];
int i = 0;
String empty = "";
while(i < solution.length){
solution[i] = homeArr[i] & awayArr[i];
i++;
}
for(int indexF = 0; indexF < solution.length; indexF++){
empty = empty + solution[indexF];
}
System.out.println(empty);
return new BinaryNumber(empty);
}
Am I understanding this right? If not could someone please explain? I'd also like to point out that this is for my homework but I'm not asking for answers/someone to do it for me. Just a point in the right direction at most.
I will gladly clarify more if it is needed (I didn't want to bog everything down).
Also this is my first post on here. I tried to keep to the formatting suggestions but I apologize if anything is sub-par.
As suggested here is the test method
public void testAnd1()
{
BinaryADT x = new BinaryNumber("111");
BinaryADT y = new BinaryNumber("000");
BinaryADT z = x.and(y);
assertNotSame(x,z);
assertNotSame(y,z);
assertEquals("000",z.toString());
}
Whenever you see the output of "toString()" like ClassName#SomeNumber, then you can be sure that toString() method is not implemented for that class (unless toString() method implementation itself is not like this).
In your case, expected value is [000], but you are getting [BinaryNumber#4896b555].
Try to implement toString() method in BinaryNumber class and return the value from this method as per assertEquals() expects. This should solve the problem.
Can you show me your test code?
1.Your expected type is different from the actual type.
2.BinaryADT class didn't overide toString method.

Simulate first call fails, second call succeeds

I want to use Mockito to test the (simplified) code below. I don't know how to tell Mockito to fail the first time, then succeed the second time.
for(int i = 1; i < 3; i++) {
String ret = myMock.doTheCall();
if("Success".equals(ret)) {
log.write("success");
} else if ( i < 3 ) {
log.write("failed, but I'll try again. attempt: " + i);
} else {
throw new FailedThreeTimesException();
}
}
I can setup the success test with:
Mockito.when(myMock).doTheCall().thenReturn("Success");
And the failure test with:
Mockito.when(myMock).doTheCall().thenReturn("you failed");
But how can I test that if it fails once (or twice) then succeeds, it's fine?
From the docs:
Sometimes we need to stub with different return value/exception for the same method call. Typical use case could be mocking iterators. Original version of Mockito did not have this feature to promote simple mocking. For example, instead of iterators one could use Iterable or simply collections. Those offer natural ways of stubbing (e.g. using real collections). In rare scenarios stubbing consecutive calls could be useful, though:
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");
//First call: throws runtime exception:
mock.someMethod("some arg");
//Second call: prints "foo"
System.out.println(mock.someMethod("some arg"));
So in your case, you'd want:
when(myMock.doTheCall())
.thenReturn("You failed")
.thenReturn("Success");
The shortest way to write what you want is
when(myMock.doTheCall()).thenReturn("Success", "you failed");
When you supply mutiple arguments to thenReturn like this, each argument will be used at most once, except for the very last argument, which is used as many times as necessary. For example, in this case, if you make the call 4 times, you'll get "Success", "you failed", "you failed", "you failed".
Since the comment that relates to this is hard to read, I'll add a formatted answer.
If you are trying to do this with a void function that just throws an exception, followed by a no behavior step, then you would do something like this:
Mockito.doThrow(new Exception("MESSAGE"))
.doNothing()
.when(mockService).method(eq());
I have a different situation, I wanted to mock a void function for the first call and run it normally at the second call.
This works for me:
Mockito.doThrow(new RuntimeException("random runtime exception"))
.doCallRealMethod()
.when(spy).someMethod(Mockito.any());
To add on to this and this answer, you can also use a loop to chain the mocked calls. This is useful if you need to mock the same thing several times, or mock in some pattern.
Eg (albeit a farfetched one):
import org.mockito.stubbing.Stubber;
Stubber stubber = doThrow(new Exception("Exception!"));
for (int i=0; i<10; i++) {
if (i%2 == 0) {
stubber.doNothing();
} else {
stubber.doThrow(new Exception("Exception"));
}
}
stubber.when(myMockObject).someMethod(anyString());
The shortest would be
doReturn("Fail", "Success").when(myMock).doTheCall();

Categories

Resources