How do I set a property on a mocked object using Mockito?

后端 未结 3 1122
执念已碎
执念已碎 2020-12-18 22:55

I have a scenario where I have to set a property of a mocked object as follows:

SlingHttpRequest slingHttpRequest= mock(SlingHttpRequest);
slingHttpRequest.s         


        
3条回答
  •  难免孤独
    2020-12-18 23:40

    I'm afraid you're misusing your mock SlingHttpRequest.

    Mockito requires you to wire up your mock's properties before you use them in your test scenarios, i.e.:

    Mockito.when(slingHttpRequest.getAttribute("search")).thenReturn(new Attribute());

    You cannot call the setAttribute(final Attribute a) method during the test like so:

    slingHttpRequest.setAttribute(someObject);

    If you do this, when the test runs, getAttribute() will return null.

    Incidently, if the code you are unit testing is going to call a setter on your mock in this way, do not use a mock. Use a stub.

提交回复
热议问题