GithubHelp home page GithubHelp logo

Comments (6)

linfan avatar linfan commented on May 2, 2024 1

PrivateAccessor.set注入以后,如果被测的方法里用了set进去的对象,@MockMethod是可以在测试的时候把调用替换成Mock方法的。比如set进去的对象是BComponent,接下来可以用@MockMethod(targetClass = BComponent.class)去换要调用的方法。

需要澄清的一件事是单元测试一般不推荐跨类进行Mock。在比较规范的单元测试里,AServiceTest类应该只做AService代码逻辑的验证。比如上面的例子,把一个BComponent类型对象bComponent放到被测的AService对象里以后,可以把不想执行的bComponent对象方法调用Mock掉。但在BComponent类型的代码里再调用CComponent的逻辑应该在BComponentTest测试类去做,因此AServiceTest里用的bComponent对象里的cComponent为空对这个测试类应该不影响。

如果确实要做跨类(跨单元)的单元测试,其实也能实现,需要在BComponent的Mock类里写对cComponent对象的Mock,但在目前的TestableMock版本里这样写测试会导致可读性下降比较多,正在重构中的0.5版本对这种场景的支持会更好一些。

from testable-mock.

linfan avatar linfan commented on May 2, 2024

如果Facade里的接口不太多,可以new一个匿名类,比如:

PrivateAccessor.set(collectBiz, "collectRouterFacade", new CollectRouterFacade() {
    ... // 这里覆写接口方法,可以根据测试需要来实现
});

用IDE辅助可以批量补齐需要覆写的方法

from testable-mock.

ningtalk avatar ningtalk commented on May 2, 2024

对于Mabatis的Mapper接口也是类似的处理方式吗?有没有其他方式

from testable-mock.

lithStudy avatar lithStudy commented on May 2, 2024

这样写有点复杂啊,尤其是接口比较多的类,这样实现起来虽然idea可以自动生成,但是代码一大堆

from testable-mock.

linfan avatar linfan commented on May 2, 2024

@lithStudy 确实比较大的临时类,可以在测试目录里单建文件来放,这样即不会让测试类变得很乱,又能在需要的时候进行复用

from testable-mock.

linfan avatar linfan commented on May 2, 2024

0.5.0版本已发布🚀

from testable-mock.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.