[JAVA]在Junit中测试私有函数的方法(junit, private, method)

eclipse中如何写一个测试私有方法的junit?
假设类Summer定义如下:
public class Summer{
   private int methodone( String argsone){
      //method code
      .......
      return 4;
   }
}

测试如下:
public class SummerTest extends TestCase {
   public void testMethodone(){
      Object rightResult = xxxxx;
      Summer example = new Summer.newInstance();
      Method m = example .getClass().getDeclaredMethod(" methodone",new Class[]{ String.class});
      m.setAccessible(true);
      Object result = m.invoke(example ,new Object[] {new String(xxxx)});
      m.setAccessible(false);
      if (result.equals(rightResult)){
         //your code
         ......
      }
   }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您要问的是关于Java计算器的Junit测试。那么我就来为您解答。 首先,JUnitJava最常用的单元测试框架之一。它可以帮助我们编写和运行测试用例,验证代码是否按照预期工作。在Java计算器的情况下,我们可以使用JUnit测试计算器的各种计算方法是否正确。 以下是Java计算器的一个示例: ```java public class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a * b; } public int divide(int a, int b) { if (b == 0) { throw new IllegalArgumentException("Cannot divide by zero!"); } return a / b; } } ``` 我们可以使用JUnit测试这个计算器类的各个方法。例如,我们可以编写以下测试用例: ```java import org.junit.Test; import static org.junit.Assert.*; public class CalculatorTest { private final Calculator calculator = new Calculator(); @Test public void testAdd() { assertEquals(4, calculator.add(2, 2)); assertEquals(0, calculator.add(-1, 1)); } @Test public void testSubtract() { assertEquals(0, calculator.subtract(2, 2)); assertEquals(-2, calculator.subtract(-1, 1)); } @Test public void testMultiply() { assertEquals(4, calculator.multiply(2, 2)); assertEquals(-1, calculator.multiply(-1, 1)); } @Test public void testDivide() { assertEquals(2, calculator.divide(4, 2)); assertEquals(-1, calculator.divide(-1, 1)); try { calculator.divide(4, 0); fail("Expected an IllegalArgumentException to be thrown"); } catch (IllegalArgumentException e) { assertEquals("Cannot divide by zero!", e.getMessage()); } } } ``` 在这个测试用例,我们分别测试了加法、减法、乘法和除法四个方法。我们使用assertEquals()方法来验证方法的返回值是否符合预期。此外,在测试除法时,我们还使用了try-catch块来捕获IllegalArgumentException异常。 总之,JUnitJava非常实用的单元测试框架,可以帮助我们编写高效的测试用例,确保代码的质量和正确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值