Mokito不返回我的值实例调用数据库

时间:2019-03-18 16:49:55

标签: java junit

我试图为我的课程做一个junit测试,我想在调用methot“ get”时模拟我的Cache变量。我的变量缓存是调用我的数据库的CacheManger的实例。但是我不知道如何测试我的方法。有人知道吗? 谢谢您的回答!

public class SlacServiceTest {
    private final Slack slack = mock(Slack.class);
    private final SlackService serviceUnderTest = new SlackService(slack);

    @Test
    public void testSomething() {
        // TODO: set mock responses here
        // Given... when... then...
    }

}

2 个答案:

答案 0 :(得分:0)

不确定我是否完全遵循您的问题。但是,要验证静态方法,可以使用PowerMockito。这是正确的方法。

您可以看到示例here

另请参阅下面创建的一个示例类

@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {

    @Test
    public void shouldVerifyParameters() throws Exception {

        //given
        PowerMockito.mockStatic(DriverManager.class);
        BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);

        //when
        sut.execute(); // System Under Test (sut)

        //then
        PowerMockito.verifyStatic();
        DriverManager.getConnection(...);

    }

更多信息

Why doesn't Mockito mock static methods?

答案 1 :(得分:0)

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

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