数组中的字符串始终返回最后一个元素,不管索引号是什么。

huangapple go评论104阅读模式
英文:

array of strings always return the last element regardless of the index number

问题

当我运行测试函数时,出现AssertionFailedError: mark::0,index::٢ =>Error in::Error set in Final Mark Function ==> expected: <Line (0): Final Mark must be a value between 0 and 60!> but was: <>。
英文:

I'm doing a test for a certain function using JUnit. The function set an error message if the input was incorrect. So, I was trying to test if the message was correct. But, the error string array, which I compare it to the error set by the function for some reason, it seams that the string array always take the last element without properly iterating over the array element.

here is the class I test With.

 package ProgramFunctions;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.String;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Vector;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class StudentGradeGenerator {

/*the error variable is used to store the error 
 *raised by any function. which is used later to in the gui
 *to display it to the user.
 */
private static String _error="";
/*the ErrorlineNumber is used to display the 
 * line of the error.
 * it's first initalized to zero, then in the 
 * InputParse function the variable is increased for every
 * line being parsed by one. 
 */
private static int ErrorlineNumber=0;

/*function to validate if the mark is:
 * 1) of type int.
 * 2) value between 0 and a maximum mark.
 */
public static int ValidateMark(String MarkName,String mark,int MaxMark)
{
	try {
		/*parse the string number in case of :
		 * success: this means that mark is of type int
		 * (then the value will be checked if it's between 0 & MaxMark).
		 * fail: an exception will occur. 
		 */
		int Mark =Integer.parseInt(mark);

		/*check if the mark between 0 & MaxMark:
		 * if it's : the value is correct and will be returned.
		 * else: an error will be raised and the function will return with value -1.
		 */
		if(Mark>=0 && Mark<=MaxMark) return Mark;

		_error ="Line ("+ErrorlineNumber+"): "+MarkName +" must be a value between 0 and "+ MaxMark +"!";
		return -1;

	}
	catch(Exception e)
	{
		/*if we reached here then that's means the mark wasn't of type int.
		 * first raise an error then return with value -1.
		 */
		_error ="Line ("+ErrorlineNumber+"): "+MarkName+" must be of type int!";
		return -1;
	}
}
	public static String getError(){
	return _error;
}
}

here is the test function:

package ProjectUnitTest;

import static org.junit.jupiter.api.Assertions.*;

import java.net.URL;

import ProgramFunctions.StudentGradeGenerator;

import org.junit.jupiter.api.Test;


class StudentGradeGeneratorTest {

@Test
	void TestFinalMark() {
		int expectedIndex = 0;
		String[] MarkInputs = new String[] { "d20", "-10", "0", "55", "60", "70" };
		int[] exepected = new int[] { -1, -1, 0, 55, 60, -1 };
	
    String[] FinalMarkExpectedErrorSet =new String[]{
		  "Line (0): Final Mark must be of type int!",
		  "Line (0): Final Mark must be a value between 0 and 60!",
		  "",
		  "",
		  "",
		  "Line (0): Final Mark must be a value between 0 and 60!"
	      };
	
	for (var mark : MarkInputs) {
		int actual = StudentGradeGenerator.ValidateMark("Final Mark", mark, 60);
		assertEquals(exepected[expectedIndex], actual,String.format("mark::%s => Returning Error in validating Final Mark Function",mark));
		assertEquals(StudentGradeGenerator.getError(),FinalMarkExpectedErrorSet[expectedIndex],String.format("mark::%s,index::%d =>Error in::Error set in Final Mark Function",mark,expectedIndex));
		expectedIndex++;
	}

}

this is what appear when I run the test function:

AssertionFailedError: mark::0,index::٢ =>Error in::Error set in Final Mark Function ==> expected: <Line (0): Final Mark must be a value between 0 and 60!> but was: <>
enter code here

although the index 2 in the FinalMarkExpectedErrorSet is an empty string, but it doesn't seem to acsses it?!

答案1

得分: 1

如果您希望在每次执行该函数后测试 _error 变量,那么在函数开始之前,您还需要重置该变量。

在代码中存在的问题是 _error 声明为 static,对于失败的测试,它实际上保留了在函数前一次执行期间分配的值。

请稍微更改函数如下,然后它应该可以正常工作。

public static int ValidateMark(String MarkName, String mark, int MaxMark) {
    try {
        
        // 在执行之前重置错误变量
        _error = "";

        /* 解析字符串数字,根据情况:
         * 成功:这意味着 mark 是 int 类型
         * (然后将检查值是否介于 0 和 MaxMark 之间)。
         * 失败:将发生异常。
         */
        int Mark = Integer.parseInt(mark);

        /* 检查标记是否介于 0 和 MaxMark 之间:
         * 如果是:值是正确的,将返回。
         * 否则:将引发错误,函数将返回值 -1。
         */
        if (Mark >= 0 && Mark <= MaxMark) return Mark;

        _error = "行 (" + ErrorlineNumber + "): " + MarkName + " 必须是介于 0 和 " + MaxMark + " 之间的值!";
        return -1;

    } catch (Exception e) {
        /* 如果我们到达这里,那意味着标记不是 int 类型。
         * 首先引发错误,然后返回值 -1。
         */
        _error = "行 (" + ErrorlineNumber + "): " + MarkName + " 必须是 int 类型!";
        return -1;
    }
}

此外,您的 assertEquals() 方法参数顺序有误。这也是您看到不正确的错误消息的原因。参数应该如下所示。

assertEquals(expectedValue, actualValue, message)

英文:

If you want to test the _error variable after each execution of the function, then you also need to reset the variable as well before the function begins.

The problem you have in the code is that _error is declared as static and for the failed test, it actually holds the value assigned during previous execution of the function.

Change the function slightly like below and it should work now.

public static int ValidateMark(String MarkName,String mark,int MaxMark)
{
    try {
        
        // reset the error variable before execution
        _error = &quot;&quot;;

        /*parse the string number in case of :
         * success: this means that mark is of type int
         * (then the value will be checked if it&#39;s between 0 &amp; MaxMark).
         * fail: an exception will occur. 
         */
        int Mark =Integer.parseInt(mark);

        /*check if the mark between 0 &amp; MaxMark:
         * if it&#39;s : the value is correct and will be returned.
         * else: an error will be raised and the function will return with value -1.
         */
        if(Mark&gt;=0 &amp;&amp; Mark&lt;=MaxMark) return Mark;

        _error =&quot;Line (&quot;+ErrorlineNumber+&quot;): &quot;+MarkName +&quot; must be a value between 0 and &quot;+ MaxMark +&quot;!&quot;;
        return -1;

    }
    catch(Exception e)
    {
        /*if we reached here then that&#39;s means the mark wasn&#39;t of type int.
         * first raise an error then return with value -1.
         */
        _error =&quot;Line (&quot;+ErrorlineNumber+&quot;): &quot;+MarkName+&quot; must be of type int!&quot;;
        return -1;
    }
}

Also you have the assertEquals() method arguments in wrong order. This is why you are seeing incorrect error message too. It's arguments should be like below.

assertEquals(expectedValue, actualValue, message)

huangapple
  • 本文由 发表于 2023年4月7日 03:14:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定