我正在开发一个应用程序,其中类 A 有 main 函数,类 B 有 getter 和 setter 方法,类 C 有一些计算。
A 类具有用户验证静态方法,以确保用户输入正确
类 B 的对象实例在 A 的主函数中创建,并且使用 B 的 getter 和 setter 方法设置“A”中验证的用户输入。
我正在使用 Junit 测试我的程序。测试 C 类中的计算函数时的问题是,A 中的用户验证没有被调用。我不想一一调用它们,但我想知道如何调用某个类及其所有静态方法,包括来自另一个类的 main ,这样我在测试时要做的就是调用 @Test 和 in 中的计算函数@setUp,调用类 A 的静态方法,以便我的 calc 函数在运行之前得到正确验证。
import code.B;
import code.C;
class A
{
private static int number1=5;
private static int number1=50;
public static final MSG_ERROR="input is null";
private static String error="";
private static boolean result=true;
p s v m(String[] args)
{
B b = new B();
int num1 = b.setValNum1(number1);
int num2 = b.setValNum2(number2);
if(!validateInput(num1,num2))
{
System.exit(1);
}
else
{
C.calc(num1,num2);
}
}
/* There are lot of validations just like this */
public static boolean validateInput(int num1,int num2)
{
if(number1 == null || number2 == null)
{
error = MSG_ERROR;
result = false;
}
return result;
}
}
class B
{
private static int num1;
private static int num2;
private getValNum1()
{
return num1;
}
private getValNum2()
{
return num2;
}
private setValNum1(int num1)
{
this.num1 = num1;
}
private setValNum2()
{
this.num2 = num2;
}
}
class C
{
public static int calc(int a,int b)
{
Sopln("add:"+(a+b));
return (a+b);
}
}
class Ctest
{
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testCalc()
{
int num1 = 4;
int num2 = 1;
int expected = 5;
/* Here if I provide num1 as null
then it will throw a error
when I have already validated
in class A for the same.
*/
int actual = C.calc(num1, num2);
assertEquals(expected,actual);
}
}
最佳答案
您需要重构代码以使其更易于测试。这是 TDD 的主要好处 - 如果代码难以测试,那么它可能难以维护、理解等。
关于您的示例代码,为了测试类 C,单元测试应该只测试 C 上的方法,就像您的示例所示。不必担心 C 的无效输入 - 这不是 C 的责任,因此不会在 C 的单元测试中对其进行测试。
为了测试验证,您将为 A 类编写一个单元测试,并使用不同的输入调用验证方法并检查结果。
关于java - 在 test() 函数中执行测试之前,调用 setUp() 中另一个类的所有静态方法,包括 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23074480/