模拟bean并在上下文级别定义其行为

时间:2015-07-07 15:04:14

标签: junit easymock

我的配置中有很少的模拟bean,它们是许多其他bean的依赖项。 我想定义它的行为,以便在其任何方法调用时返回null,而不管其输入如何。 我正在使用easyMock

TestClass
{
@Autowired 
ActualClass ac;

public Test()
{
ac.dosometing();
}
}


ActualClass
{

@Autowired
MockedClass mockedObject;

public dosomething()
{

mockedObejct.someMethod(); //i want this to be returned null in any  scenario for the test cases
}

}
}

1 个答案:

答案 0 :(得分:0)

基本上:

MockedClass mock = createNiceMock(MockedClass.class);
replay(mock);
ac.setMockedClass(mock);

使用JUnit规则和注释的现代版本将是

public class MyTest
{
    @Rule
    public EasyMockRule rule = new EasyMockRule(this);

    @Mock(type=MockType.NICE)
    MockedClass mockedObject;

    @TestSubject
    ActualClass ac = new ActualClass();

    @Test
    public void test() {
        ac.doSomething();
    }
}

class ActualClass {

    private MockedClass mockedObject;

    public void doSomething()  {
        mockedObject.someMethod();
    }

}

class MockedClass {
    public void someMethod() {}
}