2015-11-25 4 views
2

У меня проблема с приведенным ниже тестом. Класс FileUtil - это класс, который я хочу проверить.PowerMock AssertionError

import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.HashMap; 
import java.util.Map; 
import org.apache.commons.io.FilenameUtils; 
import static org.easymock.EasyMock.expect; 
import static org.powermock.api.easymock.PowerMock.mockStatic; 
import org.junit.After; 
import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.powermock.api.easymock.PowerMock; 
import org.powermock.core.classloader.annotations.PrepareForTest; 
import org.powermock.modules.junit4.PowerMockRunner; 
import static org.junit.Assert.assertEquals; 



@RunWith(PowerMockRunner.class) 
@PrepareForTest({FileUtil.class, FilenameUtils.class}) 
    public class TestBeanTest { 


    private Map<String, String> fileUrls = new HashMap<>(); 
    private final String contentType = "image/jpeg"; 
    private final String defaultName = "default"; 


    @Before 
    public void setUp() { 

    } 

    @After 
    public void tearDown() { 

    fileUrls.clear(); 
    } 

    @Test 
    public void testSanitizeFilename(){ 

    fileUrls.put("", ""); 
    fileUrls.put(" ", " "); 
    fileUrls.put("jpg", "jpg.jpeg"); 


    mockStatic(FilenameUtils.class); 

    for(Map.Entry<String, String> entry : fileUrls.entrySet()){ 
     expect(FilenameUtils.getExtension(entry.getKey())).andReturn(entry.getValue().substring(entry.getValue().lastIndexOf(". ") + 2)).anyTimes(); 
     expect(FilenameUtils.getBaseName(entry.getKey())).andReturn(entry.getValue().substring(entry.getValue().lastIndexOf(".") + 1)).anyTimes(); 

     PowerMock.replay(); 
     String result = FileUtil.sanitizeFilename(entry.getKey(), defaultName, contentType); 
     assertEquals(result, entry.getValue()); 
     PowerMock.verify(); 
    } 

    } 


    @Test(expected = MalformedURLException.class) 
    public void testSanitizeProcessedFilename() throws MalformedURLException{ 
    fileUrls.put("http://www.test.com", "image.jpeg"); 
    fileUrls.put("http://www.test.com/", "image.jpeg"); 


    mockStatic(FilenameUtils.class); 

    for(Map.Entry<String, String> entry : fileUrls.entrySet()){ 
     String fileName = processUrl(entry.key());//throws MalformedURLException 

     expect(FilenameUtils.getExtension(entry.getKey())).andReturn(entry.getValue().substring(entry.getValue().lastIndexOf(". ") + 2)).anyTimes(); 
     expect(FilenameUtils.getBaseName(entry.getKey())).andReturn(entry.getValue().substring(entry.getValue().lastIndexOf(".") + 1)).anyTimes(); 

     PowerMock.replay(); 

     String result = FileUtil.sanitizeFilename(fileName, defaultName, contentType); 
     assertEquals(result, entry.getValue()); 
     PowerMock.verify(); 
    } 

    } 

    private String processUrl(String url){ 
    URL url = new URL(entry.getKey()); 
    String path = url.getPath(); 
    String fileName; 
    int lastIndexOfSlash = path.lastIndexOf("/"); 
    if (lastIndexOfSlash >= 0) { 
      fileName = path.substring(lastIndexOfSlash + 1); 
    } else { 
      fileName = ""; 
    } 
    } 
} 

Первый метод испытания (testSanitizeFilename) выполняется успешно, но второй один (testSanitizeProcessedFilename) выдает следующее сообщение об ошибке:

Expected exception: java.net.MalformedURLException 
    java.lang.AssertionError 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:312) 
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88) 
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282) 
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86) 
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120) 
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33) 
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45) 
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118) 
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104) 
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53) 
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53) 
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53) 
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) 
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:606) 
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) 
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) 
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175) 
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107) 
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68) 

Я не уверен, что я делаю неправильно. Я попробовал PowerMock.verifyAll() и PowerMock.replayAll(), но все же получил ошибки. Может быть, неправильно, что у меня есть код в цикле? Но я не могу представить другого способа реализовать это. Любая помощь будет оценена.

+0

Мне кажется, что в стеке довольно ясно, как вы думаете, '@Test (ожидается ...' означает (doc [здесь] (http://junit.org/apidocs/org/junit/Test.html)) –

+0

Также Что такое 'processUrl' и' TestBean'? –

+0

Я обновил код. TestBean не играет роли здесь. Я удалил связанную переменную. Мне было интересно, если что-то не так с моим кодом. Я вижу исключение, но я не могу выяснить, что именно происходит. edURLException бросается, stacktrace указывает, что он ожидал один, но вместо этого получил AssertionError. Спасибо. – FunnyJava

ответ

2

вас Метод испытания с аннотацией

@Test(expected = MalformedURLException.class) 

, что это означает, что он ожидает, что тест, чтобы бросить это исключение. Как вы сказали в ваш комментарий - это исключение не выкидывается, следовательно:

Expected exception: java.net.MalformedURLException 
    java.lang.AssertionError 

, чтобы исправить это, если вы не ожидаете, что ваш тест бросить исключение, просто удалите (expected = MalformedURLException.class) из тестового аннотацию

+0

Я вижу. Большое спасибо! Я подумал, что если бы существовала вероятность того, что метод проверки исключил исключение, я должен добавить эту аннотацию в любом случае. – FunnyJava

0

Код ниже сделал трюк:

import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.HashMap; 
import java.util.Map; 
import org.apache.commons.io.FilenameUtils; 
import static org.easymock.EasyMock.expect; 
import static org.powermock.api.easymock.PowerMock.mockStatic; 
import org.junit.After; 
import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.powermock.api.easymock.PowerMock; 
import org.powermock.core.classloader.annotations.PrepareForTest; 
import org.powermock.modules.junit4.PowerMockRunner; 
import static org.junit.Assert.assertEquals; 



@RunWith(PowerMockRunner.class) 
@PrepareForTest({FileUtil.class, FilenameUtils.class}) 
    public class TestBeanTest { 


    private Map<String, String> fileUrls = new HashMap<>(); 
    private final String contentType = "image/jpeg"; 
    private final String defaultName = "default"; 


    @Before 
    public void setUp() { 

    } 

    @After 
    public void tearDown() { 

    fileUrls.clear(); 
    } 

    @Test 
    public void testSanitizeFilename(){ 

    fileUrls.put("", ""); 
    fileUrls.put(" ", " "); 
    fileUrls.put("jpg", "jpg.jpeg"); 

    //files from urls. 
    fileUrls.put(processUrl("http://www.test.com"), "image.jpeg"); 
    fileUrls.put(processUrl("http://www.test.com/"), "image.jpeg"); 

    mockStatic(FilenameUtils.class); 

    for(Map.Entry<String, String> entry : fileUrls.entrySet()){ 
     expect(FilenameUtils.getExtension(entry.getKey())).andReturn(entry.getValue().substring(entry.getValue().lastIndexOf(". ") + 2)).anyTimes(); 
     expect(FilenameUtils.getBaseName(entry.getKey())).andReturn(entry.getValue().substring(entry.getValue().lastIndexOf(".") + 1)).anyTimes(); 

     PowerMock.replay(); 

     String result = FileUtil.sanitizeFilename(entry.getKey(), defaultName, contentType); 
     assertEquals(result, entry.getValue()); 
    } 

    PowerMock.verify(); 

    } 

    private String processUrl(String url){ 
     try { 
     URL url = new URL(entry.getKey()); 
     String path = url.getPath(); 
     String fileName; 
     int lastIndexOfSlash = path.lastIndexOf("/"); 
     if (lastIndexOfSlash >= 0) { 
      fileName = path.substring(lastIndexOfSlash + 1); 
     } else { 
      fileName = ""; 
     } 
     } catch(MalformedURLException ex) { 
     return ""; 
     } 
    } 
} 

я удалил второй метод испытания и обработаны URL-адреса в первой. Кроме того, я поймал MalformedURLException в методе processUrl (...). Теперь он отлично работает.

Возможно, это было связано с тем, что я тестировал один и тот же метод (FileUrl.sanitizeFilename (...)) в двух разных методах тестирования.