我需要为一个设计很差的旧应用程序编写JUnit测试,并将大量错误消息写入标准输出.当getResponse(String request)方法行为正确时,它返回XML响应:
@BeforeClass
public static void setUpClass() throws Exception {
Properties queries = loadPropertiesFile("requests.properties");
Properties responses = loadPropertiesFile("responses.properties");
instance = new ResponseGenerator(queries, responses);
}
@Test
public void testGetResponse() {
String request = "<some>request</some>";
String expResult = "<some>response</some>";
String result = instance.getResponse(request);
assertEquals(expResult, result);
}
Run Code Online (Sandbox Code Playgroud)
但是当它得到格式错误的XML或者不理解它返回的请求并将null一些东西写入标准输出时.
有没有办法在JUnit中断言控制台输出?要抓住像这样的案例:
System.out.println("match found: " + strExpr);
System.out.println("xml not well formed: " + e.getMessage());
Run Code Online (Sandbox Code Playgroud) 假设我有一个带有 main 方法的程序,该方法使用java.util.Scanner该类来接收用户输入。
import java.util.Scanner;
public class Main {
static int fooValue = 0;
public static void main(String[] args) {
System.out.println("Please enter a valid integer value.");
fooValue = new Scanner(System.in).nextInt();
System.out.println(fooValue + 5);
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序所做的就是接收一个整数输入,并输出一个整数加 5。这意味着我可以想出一个这样的表:
+-------+-----------------+
| Input | Expected output |
+-------+-----------------+
| 2 | 7 |
| 3 | 8 |
| 5 | 12 |
| 7 | 13 |
| 11 | 16 |
+-------+-----------------+
Run Code Online (Sandbox Code Playgroud)
我需要对这组输入数据进行 JUnit 测试。处理这样的问题最简单的方法是什么?
我写了一个简单的Scala代码来练习Scala测试:
object Job {
def main(args: Array[String]) = {
val sc = new SparkContext()
println(reduceWithSum(sc))
}
def reduceWithSum(sc: SparkContext): MyClass = {
val data = Array(1, 2, 3, 4, 5)
val distData = sc.parallelize(data)
val distDataValue = distData.map(MyClass(_))
distDataValue.reduce(MyClass.sum)
}
}
Run Code Online (Sandbox Code Playgroud)
我知道为reduceWithSum()编写测试代码很容易,但为main()编写测试代码对我来说似乎很难。有什么提示吗?
这是我编写的示例测试代码:
class JobTest extends FlatSpec with Matchers {
val conf = new SparkConf().setMaster("local[*]").setAppName("Test")
val testSc = new SparkContext(conf)
it should "reduce correctly" in {
Job.reduceWithSum(testSc) shouldBe MyClass(15)
}
Run Code Online (Sandbox Code Playgroud)