java - Mokito 不返回我的值实例调用数据库
问题描述
我试图为我的班级做一个junit测试,我想在调用方法“get”时模拟我的缓存变量。我的变量缓存是调用我的数据库的 CacheManger 的一个实例。但我不知道如何测试我的方法。有人知道吗?感谢您的回答 !
private static Cache<String, Integer> cache;
private static final String QUERY = "EXEC myQuery";
public static Integer getLanguageId(String language) {
if (language == null) {
return null;
}
Integer languageId = cache.get(language);
if (languageId == null) {
throw new Exception();
}
return languageId;
}
static void configureCache() {
if (cache == null) {
//CacheManager call database
cache = CacheManager.getInstance()
.createCache(QUERY, new RuleConfigurer.StringAndIntegerRowMapper());
}
}
解决方案
这是您班级的简单单元测试。
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.cache.Cache;
import java.lang.reflect.Field;
@RunWith(PowerMockRunner.class)
@PrepareForTest({SomeClass.class})
public class SomeClassTest {
@Before
public void setup() throws IllegalAccessException {
Cache<String, Integer> cache = Mockito.mock(Cache.class);
Mockito.when(cache.get("Language1")).thenReturn(1);
Field field = PowerMockito.field(SomeClass.class, "cache");
field.set(SomeClass.class, cache);
}
@Test
public void should_return_1_when_Language1_is_the_input() throws Exception {
Integer expectedResult = 1;
Assert.assertEquals(expectedResult, SomeClass.getLanguageId("Language1"));
}
@Test
public void should_return_null_when_input_is_null() throws Exception {
Assert.assertNull(SomeClass.getLanguageId(null));
}
@Test (expected = Exception.class)
public void should_throw_exception_when_unknown_language_is_input() throws Exception {
SomeClass.getLanguageId("UnknownLanguage");
}
}
推荐阅读
- sql-server - 当对具有文本数据的列应用聚合函数时,检索到什么逻辑结果......?
- angular - *ngFor 动态创建的表单组件在表单控件中保持价值
- environment-variables - 进入屏幕后保持相同的 conda env
- python - 计算唯一的日期数以计算出现次数
- azure-webjobssdk - 如何在 Azure Webjob V3 中配置 TimerTrigger?
- r - 如何在 R 中最舒服地加载 .dta(保留标签)?
- c# - AngleSharp - 字典的 HTML 属性
- visual-studio-code - VSCode:如何让 Beautify 和 Emmet 在 .tpl 文件上运行(Smarty)?
- php - 在 PHP 中通过 CustomTranslator API 导入文档
- angular - Angular Mat-expansion-panel:选择复选框时,面板被展开并且存在的内容向上移动(附截图)?