java - JUnit - 使用可重用函数进行测试;有效性

标签 java junit

我想做的是测试我编写的一些 Lucene 代码,并且想要一些有关使用 JUnit 进行测试时的最佳实践的信息。顺便说一句,Lucene 是一个搜索引擎,您可以使用它创建一个平面文件来索引一堆数据。

所以我想测试的是这个倒排索引的创建,然后搜索索引以验证是否存在一些数据。

我的问题在代码中:

public class IndexTest {

    @Test
    public void testWriteIndexFromDB() {
        //run test
        assertTrue(something in this test); // some test for this method    
        // Is using a function like so a proper way of writing a test? 
        checkSomeDataIsReturned(); 
    }

    @Test
    public void testWriteIndexFromExcelFile() {
        //run test
        assertTrue(something in this test); // some test for this method    
        // Is using a function like so a proper way of writing a test? 
        checkSomeDataIsReturned(); 
    }

    @Test
    public void testRefreshIndexWithNewData() {
        //run test
        assertTrue(something in this test); // some test for this method    
        // Is using a function like so a proper way of writing a test? 
        checkSomeDataIsReturned(); 
    }

    // this function checks that data is returned after writing an index 
    public void checkSomeDataIsReturned(){  // not a test but does a check anyways
         results = myIndex.searchForStuff(some input);
         assertTrue(results.length > 0); // if length is zero, there is no data and something went wrong 
    }
}

总而言之,我有三个选项来编写索引,我正在测试它们每个选项的写入情况。非测试的可重用函数是编写测试的正确方法吗?或者有更好的做法吗?

最佳答案

在测试中编写可重用的代码当然是一件好事,但比这更重要的是编写易于理解的代码。一般来说,断言位于测试方法本身中,将断言移动到辅助方法可能会使您的测试难以理解。

编写可重用代码来检查期望的一种方法是使用 Hamcrest ( https://code.google.com/p/hamcrest/wiki/Tutorial ) 并构建匹配器(该库还附带了一些非常有用的集合匹配器和类似的东西)。

例如,你可以这样写:

public void
test_can_index_from_database() {
    // create your index from database

    assertThat(myIndex, containsWord('expected_word_in_index'));
}

匹配器“containsWord(String)”是您使用 hamcrest 编写的匹配器,您可以在所有测试中重复使用此逻辑。使用 hamcrest,您可以编写非常容易理解的测试。

关于java - JUnit - 使用可重用函数进行测试;有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21712360/

相关文章:

Java:如何获取音频输入的当前频率?

java - 如何使用@IfProfileValue 来测试配置文件是否处于 Activity 状态?

java - Spring Boot REST 应用测试方法

java - 查找 JUnit TestCase 中测试方法的数量

unit-testing - 在 JUnit 的方法内模拟对象

java - 如何在 JSTL 中显示格式化的日历类型?

java - 在后端和其他服务之间保存用户登录的安全方法

java - 如何为每个计划方法分配一个 Hibernate session

java - 将 JSON 反序列化为 Java 对象时映射动态字段名称

java.lang.Exception : Test class should have exactly one public constructor