Powermock/mockito не выдает исключение, когда ему говорят

Я бы предположил, что следующий тест должен пройти, но исключение никогда не выдается. Любые подсказки?

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticService.class)
public class TestStuff {

    @Test(expected = IllegalArgumentException.class)
    public void testMockStatic() throws Exception {
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(StaticService.say("hello"));
        verifyStatic();
        StaticService.say("hello");
}

}


person Jan-Olav Eide    schedule 19.02.2013    source источник


Ответы (2)


Это потому, что вы неправильно используете синтаксис doThrow... when для статических методов. Есть несколько разных способов приблизиться к этому, которые я описал в двух отдельных методах тестирования ниже.

@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticService.class})
public class StaticServiceTest {

    @Test (expected = IllegalArgumentException.class)
    public void testMockStatic1() throws Exception {
        String sayString = "hello";
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(
            StaticService.class, "say", Matchers.eq(sayString));
        StaticService.say(sayString);
        fail("Expected exception not thrown.");
    }

    @Test (expected = IllegalArgumentException.class)
    public void testMockStatic2() throws Exception {
        String sayString = "hello";
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(
            StaticService.class);
        StaticService.say(Matchers.eq(sayString)); //Using the Matchers.eq() is
                                                   //optional in this case.

        //Do NOT use verifyStatic() here. The method hasn't actually been
        //invoked yet; you've only established the mock behavior. You shouldn't
        //need to "verify" in this case anyway.

        StaticService.say(sayString);
        fail("Expected exception not thrown.");
    }

}

Для справки, вот созданная мной реализация StaticService. Я не знаю, совпадает ли он с вашим, но я убедился, что тесты пройдены.

public class StaticService {
    public static void say(String arg) {
        System.out.println("Say: " + arg);
    }
}

Смотрите также

person Matt Lachman    schedule 19.02.2013

StaticServiceTest.java с импортом:

import static org.junit.Assert.fail;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StaticService.class })
public class StaticServiceTest {

    @Test(expected = IllegalArgumentException.class)
    public void testMockStatic1() throws Exception {
        /* Setup */
        String sayString = "hello";
        PowerMockito.mockStatic(StaticService.class);

        /* Mocks */
        PowerMockito.doThrow(new IllegalArgumentException("Mockerror")).when(
                StaticService.class, "say", Matchers.eq(sayString));

        /* Test */
        StaticService.say(sayString);

        /* Asserts */
        fail("Expected exception not thrown.");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMockStatic2() throws Exception {
        /* Setup */
        String sayString = "hello";
        PowerMockito.mockStatic(StaticService.class);

        /* Mocks */
        PowerMockito.doThrow(new IllegalArgumentException("Mockerror")).when(
                StaticService.class);
        StaticService.say(Matchers.eq(sayString));

        /* Test */
        StaticService.say(sayString);

        /* Asserts */
        fail("Expected exception not thrown.");
    }

}

StaticService.java

public class StaticService {
    public static void say(String arg) {
        System.out.println("Say: " + arg);
    }
}

Тесты проходят нормально:

введите здесь описание изображения

person javaPlease42    schedule 11.11.2013