【发布时间】:2016-08-15 22:28:18
【问题描述】:
我正在尝试使用 PowerMock 进行 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 方法?
【问题讨论】:
标签: unit-testing junit liferay mockito powermock