它返回一个字符串
JUnit测试功能我有一个类里面的函数:它返回一个字符串
public String covertToLowerCase(String sliceName) {
sliceName = sliceName.trim().toLowerCase();
sliceName = sliceName.replaceAll("\\.txt$|\\.dat$", "");
return sliceName;
}
我要测试的这款使用JUnit。我创建了具有以下一个单独的测试文件:
public class MyControllerTest {
private MyController myController;
private static final String SLICE_NAME = "Hello World";
@Test
public void shouldReturnSanitizedString() throws Exception {
String expected = myController.covertToLowerCase(SLICE_NAME);
// assert that actual and expected are same
}
我无法理解如何测试这和所有其他的示例是特定于它们的功能。我只是想让函数返回一个消毒过的字符串?我怎么去解决这个问题?
要测试,首先必须准备要测试的数据,输入值,期望值=>调用具有输入值的测试函数=>获取测试中函数的实际值返回值=>声明期望值与实际价值。这是您可以使用的list of assert function。
public class MyControllerTest {
private MyController myController;
private final String SLICE_NAME = "Hello World";
private final String expected = "hello world";
@Test
public void shouldReturnSanitizedString() throws Exception {
String actual = myController.covertToLowerCase(SLICE_NAME);
// assert that actual and expected are same
assertEquals(expected, actual);
}
}
如果我想测试一些其他功能:public String createSqlFromSchema(List
@TeeJay当您有新问题时,请提出一个新问题。不要进入“评论中的更多问题”乒乓球。此外:你认为*任何人*想阅读注释中编写的源代码吗? – GhostCat
@TeeJay请注意@ GhostCat的评论。 最重要的是你需要在使用它之前了解[junit](https://www.tutorialspoint.com/junit/)。 对于你的问题,你需要测试函数'createSqlFromSchema(List
为了记录在案,更“真实世界”测试宁愿像:
public class MyControllerTest {
private MyController underTest = new MyController();
@Test(expected=NullPointerException.class)
public void testConvertToLowerCaseWithNull() {
underTest.convertToLowerCase(null);
}
以上仅仅是一个例子 - 你的方法可以决定例如抛出一个IllegalArgumentException代替。并且您想要确保您的生产代码确实实际上会为无效情况抛出异常。
@Test
public void testConvertToLowerCaseWithEmptyInput() {
assertThat(underTest.convertToLowerCase(""), is(""));
}
我推荐使用assertThat()
,连同hamcrest匹配器 - 作为所产生的代码只是更容易阅读和理解。
然后你继续添加更多的测试用例。你退后一步,你想在这里测试的东西前瞻。你要确保“e”保持“e”,“E”变成“e”......等等。
这里其他的事情:
- 尤其是做这样的输入/输出,只有当测试---做测试方法不使用领域/常量。你想尽可能多的测试你的测试自包含。为了理解我的测试 - 你只需要看看方法体。你的方法要求你查找那些常量实际包含的内容!
- 确切地说:绝对没有必要让在您的测试方法上抛出异常。它不会抛出 - 所以签名不应该公布!
- 不好命名在您的生产代码。你的方法没有只有变成小写。它也取代了内容。方法名称应该表达这一点。截至目前,该方法的名称是误导。这是你的代码可以做的最糟糕的事情:误导读者相信代码的功能,但是做更多/其他的事情!
这是什么意思“消毒”,你的正则表达式好像简单地从字符串中删除txt或dat扩展名。无论如何,你应该对'String expected =“hello world”;''进行测试,然后'String actual = myController.covertToLowerCase(SLICE_NAME);'然后'assetEquals(expected,actual)'。然后,您想要在其他不同的输入上进行相同的测试,例如:“test.txt”,“test.dat”,“test.doc”,“”,... –
我不明白。为什么你将返回值赋给一个名为'expected'的变量?这应该是“实际”。 “预期”就是你实际期待的结果。 –
测试中初始化的字段* myController在哪里?如果函数/方法是* static *,则可以在不进行初始化的情况下使用和测试。 – howlger