English 中文(简体)
如何利用PowerMock改变非静态方法
原标题:How to mock non static methods using PowerMock

我正试图改变一种内心的方法,即我的测试方法。

我的同仁们希望这样做。

public class App {
public Student getStudent() {
    MyDAO dao = new MyDAO();
    return dao.getStudentDetails();//getStudentDetails is a public 
                                  //non-static method in the DAO class
}

当我写给该方法的主人时,电磁会会改变该行。

dao.getStudentDetails();

或使上诉组在黄麻处决期间使用模拟 da子,而不是与亚洲开发银行有联系的实际 da声?

问题回答

为了摆脱模拟框架,必须注入MyDAO的物体。 你们要么可以使用像春ice这样的东西,要么只是利用工厂模式向你们提供DAO物体。 然后,在你的单位试验中,你有一个试验工厂,为你提供 mo子,而不是真正的 objects子。 之后,你可以写成法典,例如:

Mockito.when(mockDao.getStudentDetails()).thenReturn(someValue);

如果你没有机会进入Mockito,你也可以利用PowerMock实现同样的目的。 例如,你可以做以下工作:

@RunWith(PowerMockRunner.class)
@PrepareForTest(App.class)
public class AppTest {
    @Test
    public void testGetStudent() throws Exception {
        MyDAO mockDao = createMock(MyDAO.class);
        expect(mockDao.getStudentDetails()).andReturn(new Student());        
        replay(mockDao);        

        PowerMock.expectNew(MyDAO.class).andReturn(mockDao);
        PowerMock.replay(MyDAO.class);         
        // make sure to replay the class you expect to get called

        App app = new App();

        // do whatever tests you need here
    }
}




相关问题
how to update a textbox from a static class?

This is driving me nuts. I have a working text based application. It has many many variables which now need a GUI. I m starting with the basics. Whenever some data is sent to my log, I want it to ...

Java method help [duplicate]

Possible Duplicate: Static method in java Ok, so I m working on a project for a class I m taking.. simple music library. Now I m having some issues, the main issue is I m getting "non-static ...

Non static members as default parameters in C++

I m refactoring a large amount of code where I have to add an extra parameter to a number of functions, which will always have a value of a member of that object. Something like class MyClass { ...

Triggering a non-static class from a static class?

I am writing a class library(API) in C#. The class is non-static and contains several public events. Is it possible to trigger those events from a static method in a separate class? For example... ...

热门标签