我尝试为我的类进行 junit 测试,我想在调用方法“get”时模拟我的 Cache 变量。我的变量缓存是调用我的数据库的 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());
}
}
最佳答案
这是您的类(class)的简单单元测试。
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");
}
}
关于java - Mokito 不返回我的值实例调用数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55226286/