How to use stubs in JUnit and Java?

℡╲_俬逩灬. 提交于 2019-12-30 01:12:09

问题


I have worked with JUnit and Mocks but I'm wondering, what are the differences between Mocks and Stubs in JUnit and how to use Stubs in JUnit, Java? And as Mocks that have EasyMock, Mockito and so on, what does Stubs uses in Java?

Please give some example code for Stubs in Java.


回答1:


To use stubs in junit you don't need any frameworks.

If you want to stub some interface just implement it:

interface Service {
    String doSomething();
}

class ServiceStub implements Service {
    public String doSomething(){
        return "my stubbed return";
    }
}

Then create new stub object and inject it to tested object.

If you want to stub a concrete class, create subclass and override stubbed methods:

class Service {
    public String doSomething(){
        // interact with external service
        // make some heavy computation
        return "real result";
    }
}

class ServiceStub extends Service {
    @Override
    public String doSomething(){
        return "stubbed result";
    }
}



回答2:


It doesn't matter the framework or technology in my opinion. Mocks and stubs could be defined as follows.

A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.

A mock object is a fake object in the system that decides whether the unit test has passed or failed. It does so by verifying whether the object under test interacted as expected with the fake object.

Perhaps these images can clarify the interactions between a stub an mock.

Stub

Mock




回答3:


In general - Mock means implement some behavior, stubs - just supply some data. in other words preferable use the work mock when you need to demonstrate that it changes/keeps some state

use the word stub when your classes only expose the internal state. indeed you can use mock everywhere, and stub is just subset of mock



来源:https://stackoverflow.com/questions/31890991/how-to-use-stubs-in-junit-and-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!