简体   繁体   English

spring 引导应用程序的单元测试

[英]Unit Tests for spring boot application

I have never used JUnit testing before.I need to test my code with JUnit.我以前从未使用过 JUnit 测试。我需要用 JUnit 测试我的代码。 I have been searching google for all day but the problem is that I found examples using Mockito but in my code I didn't use dependency injections(@Autowired).我整天都在搜索谷歌,但问题是我找到了使用 Mockito 的示例,但在我的代码中我没有使用依赖注入(@Autowired)。 How can i use it for these methods?我如何将它用于这些方法?

Thanks in advance.提前致谢。

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();
}

}

You can extract WordDao to class level as a field.您可以将 WordDao 提取到 class 级别作为字段。 Create set method.创建集合方法。 After that in unit test you can mock WordDao and control what will be result of methods call.之后在单元测试中,您可以模拟 WordDao 并控制方法调用的结果。 For the second method it something like:对于第二种方法,它类似于:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM