简体   繁体   English

用main方法用Java编写单元测试

[英]Writing a Unit test in Java with main method

I have a few methods in my class 我班上有几种方法

public class StringChecking
{
public static void main(String[] args);
public void stringChecker(String text, int number); //takes a string and prints that out. 
}

I want to write Unit test to test the ' stringChecker() ' method. 我想编写单元测试来测试' stringChecker() '方法。 I was wondering how I would go about doing that. 我想知道我将如何去做。 When I create an object of type StringChecking in my JUnit Testing class, I can't seem to access stringChecker() method from that instance. 当我在JUnit Testing类中创建StringChecking类型的对象时,似乎无法从该实例访问stringChecker()方法。

StringChecker method prints out certain number of words of the text passed in depending on the parameter.I wish to check to see if the first 10 words getting printed out are same as the expected results. StringChecker方法根据参数打印出传入文本的一定数量的单词,我希望检查打印出的前10个单词是否与预期结果相同。

JUnit test class JUnit测试类

String expected = "My name is";
asserEquals(expected, actual);

I'm guessing I will have make my stringChecker method return something, inorder to do the check. 我猜我将让我的stringChecker方法返回一些内容,以便进行检查。 But I don't understand why I can't access the method from testing class. 但是我不明白为什么我不能从测试类访问该方法。

The code would be easier to test if instead of printing the numbers, the method returned them to the caller. 该方法是否更容易测试代码(而不是打印数字),而不是将数字返回给调用方。

If you want to test the actual printing, you could set a spy object to System.out that instead of printing collects the data. 如果要测试实际的打印,可以将一个间谍对象设置为System.out ,而不是打印来收集数据。 Then your test can assert the correctness of that output. 然后,您的测试可以断言该输出的正确性。

If you're attempting to assert values coming back , then your method signature is incorrect - it should be returning a String . 如果您尝试断言返回的值 ,则您的方法签名不正确-它应该返回String From there, you can perform the usual operation with JUnit (your main method serves no purpose in this context): 从那里,您可以使用JUnit执行通常的操作(在这种情况下,您的main方法没有任何作用):

@Test
public void checkString() {
    String expected = "My name is";
    int actual = 3; // assuming words in string
    StringChecking testObj = new StringChecking();
    assertEquals(expected, testObj.stringChecker(expected + " Bob", 3);
}

Merely printing out values asserts/validates nothing - they provide visual confirmation, which can be often incorrect or invalid. 仅打印出值不会声明/验证任何内容-它们提供视觉确认,通常可能是不正确或无效的。

Java has to know what those values are, and the most direct way to do that is to return the value you need back. Java必须知道这些值是什么,最直接的方法是返回所需的值。

This isn't to say that you can never test a void method, but that in this case, it's not appropriate. 这并不是说您永远无法测试void方法,但是在这种情况下,这是不合适的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM