[英]JUnit test data in static or non static methods
想知道哪个好。
我必须将一些 JUnit 测试数据保存在不同的文件中。 让我们称之为TestingData.java
。 我想到了两种方法。
测试数据.java
public class TestingData {
protected String getHelloWorld() {
return "Hello World";
}
}
测试数据.java
public class TestingData {
public static String getHelloWorld() {
return "Hello World";
}
}
我可以通过 extends TestingData
类在我的测试服务中像这样调用第一种方式
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest extends TestingData {
@Test
public void helloWorldTest() {
assertEquals("Hello World", getHelloWorld());
}
}
通过调用静态函数TestingData.getHelloWorld()
在我的测试服务中调用Second Way
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
@Test
public void helloWorldTest() {
assertEquals("Hello World", TestingData.getHelloWorld());
}
}
想知道在干净的代码原则中哪种方式更好
答案可能与“干净的代码”无关,而是根据您当前和未来的用例而有所不同。
以第一种方式扩展夹具类会产生一个重要的限制 - 您将无法扩展任何其他基类,并且这种情况在单元测试中经常发生。
第二种方式中的静态方法不能被覆盖。
你可以使用第三种方式,一个带有默认方法的接口。 这不会限制你使用特定的基类,如果你将来需要它,它的默认方法可能会被覆盖:
public interface TestingData {
default String getHelloWorld() {
return "Hello World";
}
}
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest implements TestingData {
@Test
public void helloWorldTest() {
assertEquals("Hello World", getHelloWorld());
}
}
如果您有多个测试类共享同一个父类。 您可以定义abstract
类并放置所有公共属性和行为。
,并且我建议将静态内容声明为static final
而不是硬编码。
通过这种方式,您可以选择创建一个方法并在每个测试用例中从子级调用它,如下所示:
public abstract class TestingData {
private static final GET_HELLO_WORLD = "Hello World";
public void setUp() {
// common setUp
}
protected String getHelloWorld() {
return GET_HELLO_WORLD;
}
}
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest extends TestingData {
@Before
public void setUp() {
super.setUp();
// Add more settings
}
@Test
public void helloWorldTest() {
assertEquals("Hello World", getHelloWorld());
}
}
, 或者直接从孩子那里调用常量
public abstract class TestingData {
protected static final GET_HELLO_WORLD = "Hello World";
public void setUp() {
// common setUp
}
}
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest extends TestingData {
@Before
public void setUp() {
super.setUp();
// Add more settings
}
@Test
public void helloWorldTest() {
assertEquals(callTargetTestMethod(), GET_HELLO_WORLD);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.