Mock study

Mockstudy


Why we need mock?


About unit testidea——reason why need mock


1.The idea of unittesting is that we want to test our code without testing thedependencies.This test allows you to verify that the code beingtested works, regardless of it's dependencies.


2.If the code Iwrite works, and my dependencies also work , then they should worktogether.


3.In the real world,software always need dependence injection.


The dependenciescome from:


—— library weload in IDE.


—— For MVCframework is always used in web application, controllers havedependencies comes from services and services have dependencies ondata access objects(DAOs).


Three key mocking concepts

Stubbing

Stubbing is youexpect your fake’s behaviour return what you want .

When(mockObject.behaviour(params…)).return(expect_value)

Can stub privatebehaviours?

There's no need tostub private behaviours.The reason is :

– Privatebehaviours can not be used in other class.

– Our unit testscan not cover private methods.

Setting expectations

One of the keyfeatures of a fake is the ability to tell the fake what you expectwhen your test runs. For example, you may expect that a specificfunction be invoked exactly 3 times.

MockObject.expects(once()).method(“methodName”).withAnyArguments().will(returnValue(value));



Setting expectationsis the process of telling your fake what and how you expect to happento it. Remember that since it’s a fake, nothing actually happens.


According tohttp://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs

Verifying

Verifying is judgingif some behaviour really happened.


How Spring use mockito?




Dependecy injectionis very common used in MVC. It always encapsulate the injection toprivate fields. Which make it difficult for testing stuff.


It is convenient touse Mockito to solve this problem.


First, ourdependency class:
















It will be used inAccountService for accessing database.













When we write unittest for AccountService, It is better to mock AccountMapper class.Wedo like this:


1.Annotation@InjectMocks for Testing class.Here, our testing class isAccountService.


2.Annotation @Mockfor the dependency class(injected in AccountService) AccountMapper.


3.In @Beforeannotation method, invoke initMocks method.This method invokesspecial Mockito call (MockitoAnnotations.initMocks(this)) toinitialize annotated fields. It will do something like


MyObject myObject =mock(MyObject.class)


Without this call,these objects would be null. Common mistake with this approach is toforget this invocation.















4.Then, we can usethe mock object accountMapper to mock everything we would like it tobe.



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值