首页 > 解决方案 > 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());
    }
}

标签: javajunit

解决方案


这是您班级的简单单元测试。

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

推荐阅读