如何将数据传递给Junit中的测试类

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

How to pass data to test class in Junit

问题

我对JUnit还不熟悉不知道如何测试这种类型的代码

package input.commandline;

import java.util.InputMismatchException;
import java.util.regex.Pattern;

public class ReadFilePath extends CommandLineInput {

    public String perform() {
        String path = scanner.nextLine();
        String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";
        boolean isMatched = Pattern.matches(regularExpression, path);
        if (isMatched) {
            return path;
        } else {
            throw new InputMismatchException();
        }
    }
}

这是我的测试类

package input.commandline;

import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.*;

public class ReadFilePathTest {

    @Test
    public void sampleTest() throws Exception {
        //        ReadFilePath readFile = new ReadFilePath();
        //
        //        readFile.perform();

        Assert.assertEquals("sam", "sam");
    }
}

我不知道如何向下面这行代码传递数据
String path = scanner.nextLine();
英文:

I am new to JUnit and I do not know how to test this kind of code.

    package input.commandline;

import java.util.InputMismatchException;
import java.util.regex.Pattern;

public class ReadFilePath extends CommandLineInput{

    public String perform(){
        String path = scanner.nextLine();
        String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";
        boolean isMatched = Pattern.matches(regularExpression,path);
        if(isMatched){
            return path;
        }else {
            throw new InputMismatchException();
        }

    }
}

this is my test class

package input.commandline;

import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.*;

public class ReadFilePathTest {

    @Test
    public void sampleTest() throws Exception{
//        ReadFilePath readFile = new ReadFilePath();
//
//        readFile.perform();

        Assert.assertEquals("sam","sam");
    }
}

I do not know how to pass data to
String path = scanner.nextLine();
this line

答案1

得分: 1

以下是翻译好的内容:

我会将扫描器或输入流注入到被测试的类中,从外部传入,或者将其作为方法参数传递,因为这是类ReadFilePath的一个依赖项。

如果你在ReadFilePath类或其父类内部使用了new Scanner(System.in),那么就无法对其进行模拟或替换。

Scanner类是一个final类,因此我们无法进行模拟。

你可以更新你的类,使其在构造函数或方法参数中接受InputStream,代码如下所示:

接受InputStream作为参数的代码:

public class ReadFilePath {

  public String perform(InputStream is){
    Scanner scanner = new Scanner(is);
    String path = scanner.nextLine();
    String regularExpression = "([a-zA-Z]:)?(\\\\[a-zA-Z0-9_-]+)+\\\\?";
    boolean isMatched = Pattern.matches(regularExpression, path);
    if(isMatched){
      return path;
    }else {
      throw new InputMismatchException();
    }
  }
}

测试可以如下所示:

  @Test
  public void test() throws Exception {
    String inputForTest = "input";
    InputStream is = new ByteArrayInputStream(inputForTest.getBytes());
    ReadFilePath readFilePath = new ReadFilePath();
    String result = readFilePath.perform(is);
    //断言结果
  }
英文:

I would inject a scanner or input stream into the class under test from outside or pass it as a method parameter because it is a dependency for the class ReadFilePath.

If you have done new Scanner(System.in) inside the ReadFilePath class or its parent, then you can not mock it or replace it.

Scanner class is final class so mocking is not an option for us.

You can update your class to take InputStream into constructor or method param as below.

Code taking InputStream taking as param:

public class ReadFilePath {

  public String perform(InputStream is){
    Scanner scanner = new Scanner(is);
    String path = scanner.nextLine();
    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";
    boolean isMatched = Pattern.matches(regularExpression,path);
    if(isMatched){
      return path;
    }else {
      throw new InputMismatchException();
    }

  }
}

Test can be like this

  @Test
  public void test() throws Exception {
    String inputForTest = "input";
    InputStream is = new ByteArrayInputStream(inputForTest.getBytes());
    ReadFilePath readFilePath = new ReadFilePath();
    String result = readFilePath.perform(is);
    //assert result
  }

答案2

得分: 1

以下是您要翻译的内容:

注意: 代码部分已被保留为英文原文。

It would be great if you don't call `String path = scanner.nextLine();` directly inside your code. You might have to consider restructuring the code to perform the read the input from a separate method, so that you can test your functionality properly and to simulate input console reads.

public class ReadFilePath{
    public void readAndPerform() {
        Scanner scanner=new Scanner(System.in);
        String path = scanner.nextLine();
        perform(path);
    }
    
    public String perform(String path){
         String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";
         boolean isMatched = Pattern.matches(regularExpression,path);
         if(isMatched){
             return path;
         }else {
             throw new InputMismatchException();
         }
    }
}

You can write your test case like below :
public class ReadFilePathTest {

    @Test
    public void sampleTest() throws Exception{
        String data = "testValueHere";
        InputStream stdin = System.in;
        ReadFilePath obj=new ReadFilePath();
        try {
          System.setIn(new ByteArrayInputStream(data.getBytes()));
          Scanner scanner = new Scanner(System.in);
          String path=scanner.nextLine();
          Assert.assertEquals("testValueHere",obj.perform(path));
        } finally {
          System.setIn(stdin);
        }
    }
}
英文:

It would be great if you don't call String path = scanner.nextLine(); directly inside your code. You might have to consider restructuring the code to perform the read the input from a separate method, so that you can test your functionality properly and to simulate input console reads.

public class ReadFilePath{
	public void readAndPerform() {
		Scanner scanner=new Scanner(System.in);
		String path = scanner.nextLine();
    	perform(path);
	}
	
    public String perform(String path){
         String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";
         boolean isMatched = Pattern.matches(regularExpression,path);
         if(isMatched){
             return path;
         }else {
             throw new InputMismatchException();
         }
    }
}

You can write your test case like below :

public class ReadFilePathTest {

	@Test
    public void sampleTest() throws Exception{
		String data = "testValueHere";
		InputStream stdin = System.in;
		ReadFilePath obj=new ReadFilePath();
		try {
		  System.setIn(new ByteArrayInputStream(data.getBytes()));
		  Scanner scanner = new Scanner(System.in);
		  String path=scanner.nextLine();
	      Assert.assertEquals("testValueHere",obj.perform(path));
		} finally {
		  System.setIn(stdin);
		}
    }
}

huangapple
  • 本文由 发表于 2020年9月19日 21:33:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63969386.html
匿名

发表评论

匿名网友

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

确定