2016-08-15 52 views
0

我試圖使用PowerMock進行JUnit測試,但我遇到了一個問題。這裏是我的代碼:使用PowerMock在Liferay中進行JUnit測試

public class MyGreeting extends MVCPortlet { 

    public static final String GREETING="greeting"; 
    private static final String DEFAULT_GREETING="MY DEFAULT GREETING MESSAGE"; 
    private static final Log _log = LogFactoryUtil.getLog(MyGreeting.class.getName()); 

    @Override 
    public void render(RenderRequest req,RenderResponse res) 
      throws IOException, PortletException { 
     PortletPreferences prefs = req.getPreferences(); 
     req.setAttribute(GREETING, prefs.getValue(GREETING, DEFAULT_GREETING)); 
     super.render(req,res); 
    } 

而且我需要進行JUnit測試。我創造了另一個測試包,新MyGreetingTest.java文件,並拿出來驗證碼:

public class MyGreetingTest extends Mockito{ 

@BeforeClass 
public static void setUpBeforeClass() throws Exception { 
} 

@AfterClass 
public static void tearDownAfterClass() throws Exception { 
} 

private MyGreeting portlet; 

@Before 
public void setUp() throws Exception { 
    portlet = new MyGreeting(); 
} 

@After 
public void tearDown() throws Exception { 
} 

@Mock 
public RenderRequest request = mock(RenderRequest.class); 

@Mock 
PortletPreferences preferences = mock(PortletPreferences.class); 


@Test 
public final void renderTest() throws IOException, PortletException { 

    when(request.getPreferences()).thenReturn(preferences); 
    when(preferences.getValue(MyGreeting.GREETING, null)).thenReturn(value); 

    portlet.render(request, null); 
    String result = request.getAttribute(MyGreeting.GREETING).toString(); 
    assertEquals(result, value); 
} 

但我有NullPointerException異常,因爲我們不能適用getAttribute方法mock-request。你能告訴我如何解決這個問題嗎?如何使用Mockito測試使用getAttribute方法的方法?

回答

0

我認爲你需要模擬你的方法

股票股票=模擬(Stock.class); 012(stock.getPrice())。thenReturn(100.00); //模擬實現 when(stock.getValue())。thenCallRealMethod(); //真正實施

+0

這真是奇怪。你建議粘貼這段代碼而不是'when/thenReturn'塊? – German

+0

不,我只是建議你如何嘲笑這個方法! – Akash