【问题标题】:JUnit Tests for Liferay MVCPortlet using PowerMock使用 PowerMock 对 Liferay MVCPortlet 进行 JUnit 测试
【发布时间】: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


    【解决方案1】:

    我认为你需要模拟你的方法

    库存 = 模拟(Stock.class); 当(stock.getPrice()).thenReturn(100.00); // 模拟实现 当(stock.getValue()).thenCallRealMethod(); // 真正的实现

    【讨论】:

    • 这很奇怪。您建议粘贴此代码而不是 when/thenReturn 块?
    • 不,我只是建议你如何模拟该方法!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多