想重构,就要有单元测试。没有单元测试,还真不敢随便重构。
没事先写个例子出来:
1、包结构如下:

2、写个要测试的类HelloWorld:
package com.lippeng;
public class HelloWorld {
public int helloJunit(int aInt) {
System.out.println("Hello Junit");
return aInt;
}
}
3、整个工程测试入口AllTests:
package com.lippeng;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ HelloWorldTest.class })
public class AllTests {
}
4、测试这个类之前,想做的一些必要的初始化,可以放在其父类中。当然,放在测试类中也可以。抽象类BaseTest:
package com.lippeng;
import org.junit.Before;
public abstract class BaseTest {
protected HelloWorld helloWorld;
@Before
public void initHelloWorld() {
helloWorld = new HelloWorld();
}
}
5、测试类 HelloWorldTest:
package com.lippeng;
import static org.junit.Assert.*;
import org.junit.Test;
public class HelloWorldTest extends BaseTest {
@Test
public void helloJunitTest() {
assertNotNull(helloWorld.helloJunit(3));
assertSame(3, helloWorld.helloJunit(3));
assertNotSame(2, helloWorld.helloJunit(3));
assertNotSame(4, helloWorld.helloJunit(3));
}
}
本文详细阐述了在进行代码重构前,通过编写单元测试来确保代码质量和稳定性的重要性。介绍了如何构建包结构、编写测试类和测试入口,以及如何在测试类中进行必要的初始化操作。此外,还分享了在测试类中实现测试方法的实践,包括使用断言进行验证。通过实例演示了如何将测试工作融入到日常开发流程中,以提高软件开发的效率和质量。

1067

被折叠的 条评论
为什么被折叠?



