Mocking up WifiManager for Android Unit Testing

前端 未结 3 889
时光说笑
时光说笑 2021-01-13 08:30

I\'m trying to implement some unit tests for a couple of classes that rely on WifiManager and the returned ScanResults. What I\'d like to do is be able to control the ScanR

3条回答
  •  孤城傲影
    2021-01-13 09:21

    Create an abstraction around WifiManager. Use this for your mocking. Mocking stuff you don't own is hard and brittle. If done right you should be able to switch the internals, plus you'll end up with a better mockable API.

    For your testing you can stub/fake the manager to you hearts content. For production you'll pass in a concrete instance.

    With regards to your point about changing your code just to make it testable that is incorrect. Firstly you should mock roles not types as discussed in the paper below. Google for more info.

    Secondly creating an abstraction around third party code is a best practice as stated by the dependency inversion principle in SOLID. You should always depend on abstractions rather than concrete implementations whether you are unit testing or not.

    http://www.objectmentor.com/resources/articles/dip.pdf http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

提交回复
热议问题