如何为add方法编写junit testCase?

发布于 2024-10-29 18:10:20 字数 457 浏览 0 评论 0原文

这是多项式的 add 方法

public Polynomilal add (Polynomial poly){

//getA()..etc getters for the coefficients of the polynomial.

    MyDouble aVal=getA().add(poly.getA());
    MyDouble bVal=getB().add(poly.getB());
    MyDouble cVal=getC().add(poly.getC());
    Polynomial addedPoly=new Polynomial(aVal, bVal, cVal);
    return addedPoly;
}

,add 方法的测试用例以

public void testAdd() {
........
........

}

here is the add method for polynomial

public Polynomilal add (Polynomial poly){

//getA()..etc getters for the coefficients of the polynomial.

    MyDouble aVal=getA().add(poly.getA());
    MyDouble bVal=getB().add(poly.getB());
    MyDouble cVal=getC().add(poly.getC());
    Polynomial addedPoly=new Polynomial(aVal, bVal, cVal);
    return addedPoly;
}

and the test case for add method starts with

public void testAdd() {
........
........

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

手长情犹 2024-11-05 18:10:20

以下是一些基础知识...

单元测试的总体思路是将“您想要的”与“您得到的”进行比较。一个简单的断言就像

assertEquals("it better work!", 4 /* expected */, 2 + 2);

如果你知道 aVal 应该是什么,你可以做

assertEquals("aVal should be this", <what you expecte it to be>, aVal);

“double”值有一个特殊的细节,因为舍入导致它们通常不完全是你所期望的,所以你说:

assertEquals("some double value", 1.555555d, 1.0d + 5.0d / 9.0d, .001); // within .001? ok!

无论如何,这就是单位的要点测试。对你能看到的事物的断言。非常方便的东西。

(assertEquals 等都可以从 TestCase 静态访问,大多数单元测试都源自 TestCase。)

Here's some of the basics...

The general idea of a unit test is to compare "What you want" with "What you got". A simple assertion is like

assertEquals("it better work!", 4 /* expected */, 2 + 2);

If you know what aVal should be, you can do

assertEquals("aVal should be this", <what you expecte it to be>, aVal);

There's a special detail for "double" values, because roundoff causes them to often be not exactly what you expect, so you say:

assertEquals("some double value", 1.555555d, 1.0d + 5.0d / 9.0d, .001); // within .001? ok!

Anyway, that's the gist of unit tests. Assertions of things you can see. Very handy stuff.

(assertEquals, and friends, are all statically accessible from TestCase, which most unit tests descend from.)

残疾 2024-11-05 18:10:20

除了大卫的回答之外,我建议您使用此处描述的自定义断言模式。另外,我会考虑对输入和预期数据使用参数化测试,如此处所述,并使用一些特定于 JUnit 的测试例如以下内容

希望这有帮助!

As addition to david's answer I recommend you to use Custom Assertion pattern described here. Also I'd consider using parametrized tests for input and expected data as described here and using some JUnit specific examples like the following.

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文