Spring Boot应用程序的单元测试

问题描述 投票:0回答:1

我以前从未使用过JUnit测试。我需要使用JUnit测试我的代码。我整天都在Google搜索,但问题是我发现了使用Mockito的示例,但是在我的代码中我没有使用依赖项注入(@Autowired)。如何将它们用于这些方法?

提前感谢。

public class WordService {

public WordService() {

}


public static String upperCaseFirst(String value) {
    char[] listChar = value.toCharArray();
    listChar[0] = Character.toUpperCase(listChar[0]);
    return new String(listChar);
}

/**
 * Find and return the search word
 * @param name
 * @return the word sought or null if not found
 */
public Word findWordByName(String name){

    String nameUpper = upperCaseFirst(name);

    WordDao w = new WordDao();
    Word found = w.findWord(nameUpper);

    List<String> definitions = new ArrayList<>();

    if(found != null) {
        for(int i=0; i<found.getDefinition().size(); i++) {
            StringBuffer defBuffer = new StringBuffer();

            String definitionFound = found.getDefinition().get(i);
            definitionFound = definitionFound.replace("\n", "");

            defBuffer.append(definitionFound);
            defBuffer.append("_");

            definitions.add(i, defBuffer.toString());
        }
        found.setDefinition(definitions);
    }
    return found;
}


/**
 * 
 * @return Return a list of words
 */
public List<Word> findAllWord(){

    WordDao w = new WordDao();
    return w.findAllWords();
}

}
java spring-boot junit java-ee-6
1个回答
0
投票

您可以将WordDao提取为类级别的字段。创建设置方法。之后,在单元测试中,您可以模拟WordDao并控制方法调用的结果。对于第二种方法,它类似于:

WordDao wMocked = Mock(WordDao.class)
Word word1 = new...
Word word2 = new...
List<Word> words = List.of(word1, word2);
when(w.findAllWords()).thenReturn(words);
WordService ws = new WordService();
ws.setWordDao(wMocked);
Assert.equals(words, ws.findAllWords);
© www.soinside.com 2019 - 2024. All rights reserved.