Observe two pieces of code and answer the following questions:
(1) Error code found;
(2) Try to write the test case, do not execute the fault part;
(3) Execute the fault part, but do not appear error condition;
(4) An error condition occurs, but failure does not occur.
Code One:
Public intFindLast (int[] x,inty) {//effects:if X==null ThrowNullPointerException//else return the index of the last element//In x that equals Y.//If No such element exists, return-1 for(inti=x.length-1; i >0; i--){if(X[i] = =y) {returni;}}return-1;}//test:x=[2, 3, 5]; y = 2//expected = 0
(1) The termination condition for the For loop should be i<=0;
(2) x=[],y=2;
This is because x is empty, so do not enter for loop, directly return nullpointerexception;
Excepted:NullPointerException,
Actual:nullpointerexception;
(3) x=[1,2,3],y=2;
Here the last value of Y is not at x[0], and in x[1], so the For loop does not perform to the "i>=0" condition out, so there is no error state;
Excepted:1,
Actual:1;
(4) x=[3,4,5],y=2;
Although the error condition is performed here, there is no value equal to Y in X, so the result is correct, so there is no failure;
excepted:-1,
actual:-1;
Code two:
Public Static intLastzero (int[] x) {//effects:if X==null ThrowNullPointerException//else return the index of the last 0 in X.//Return-1 If 0 does not occur in X for(inti =0; i < x.length; i++){if(X[i] = =0){returni;}} return-1;}//test:x=[0, 1, 0]//expected = 2
(1) The direction of the for loop execution is reversed and should not be started by i=0, but should be reduced from x.length-1;
(2) Here anyway the code will execute into the for loop, so there is no such sample; (unlike the previous question, the fault in the previous question is a judging condition for the For loop, and when x is empty, the For loop will appear when the first step is performed on the I assignment.) NullPointerException is not executed to fault, and the fault in this question is the entire for loop, so as long as the For loop is entered into the fault)
(3) x=[1]; Here the execution will enter the for loop, that is, to enter the fault, but because there is only one element in X, so there is no positive and negative problem of loop execution, so there is no error state;
excepted:-1,
actual:-1;
(4) x=[1,0,2]; The error state occurs when the code executes, but since there is only one 0 in X, it does not affect the result regardless of whether it is executing for loop or backwards, so no failure is occurring;
Excepted:1,
Actual:1.
Liam's Software Testing Learning Journey (ii): Finding two examples of errors