简体   繁体   English

如何使用EasyMock测试模拟方法

[英]How to test mock method with EasyMock

I try to test a method in my object using easyMock. 我尝试使用easyMock在对象中测试一种方法。 I do something like this: 我做这样的事情:

MyObject myObject = createMock(MyObject.class);
expect(myObject.someMethod()).andReturn(someReturn);
replay(myObject);
myObject.methodIwantToTest(); // here assertion or sth like this
verify(myObject);

The code like this is throw an exception that methodIwantToTest is not expected. 像这样的代码将引发异常,即methodIwantToTest是不可预期的。 How to test this method? 如何测试这种方法?

Mocks are intended to replace a dependency for a class your are testing. 模拟旨在替换您正在测试的类的依赖关系。 That means if you are testing class A, and it calls a method on class B, you mock class B with the expected behavior, so you can test A in isolation. 这意味着,如果您正在测试类A,并且在类B上调用了一个方法,则可以使用预期的行为模拟类B,以便可以独立地测试A。

You are receiving that error because when you mock a class, you are not supposed to use it normally. 之所以收到该错误,是因为在模拟一个类时,您不应该正常使用它。 You are supposed to set up expectations, and then use your mock in concert with another class. 您应该设定期望,然后将您的模拟游戏与另一个课程一起使用。 You never set up the expectation that methodIwantToTest should be called, so when you called it, there is an error (since it wasn't expected by the framework). 您从来没有期望methodIwantToTest应调用methodIwantToTest的期望,因此,在调用它时,会出现错误(因为框架未预期methodIwantToTest错误)。

That said, you can create a partial mock. 也就是说,您可以创建部分模拟。 See this documentation and look for "Partial", where you only mock certain methods. 请参阅此文档,并查找“部分”,您仅在其中模拟某些方法。

Just as hvgotcodes said, Mocks are objects used to simulate the dependencies of your Class Under Test(CUT) so that your CUT can be tested in isolation from other code. 就像hvgotcodes所说的那样,Mocks是用于模拟被测类(CUT)的依赖关系的对象,以便可以与其他代码隔离地测试CUT。

Though available, it is generally not advisable to use Partial Mocks . 尽管可用,但通常不建议使用Partial Mocks The argument placed is that, when the design of your software is good the use of partial mocks is not necessary. 所提出的论据是,当您的软件设计良好时,不必使用部分模拟。 However in some scenarios it may be important to use partial mocks. 但是,在某些情况下,使用部分模拟可能很重要。 In your case, partial mocking can be done as follows, 在您的情况下,可以如下进行部分模拟,

@Test
public void testSomething(){
    MyObject myObject = createMockBuilder(MyObject.class)
       .addMockedMethod("someMethod").createMock();
    expect(myObject.someMethod()).andReturn(someReturn);
    replay(myObject);
    myObject.methodIwantToTest();
    verify(myObject);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM