简体   繁体   中英

With Mockito, if I inject an object into my mock with @InjectMocks how do I avoid nulling out other objects?

public class TargetObjectWrapper extends TargetObject {
   @Mock SomeObject myMockOfSomeObject;
   @InjectMocks TargetObject targetObject;

   public TargetObjectWrapper(){
       this.targetObject = mock(originalObject);

       //doAnswer(...).when(...) methods
   } 

   //Override other methods of TargetObject
 }

I'm trying to inject a specific mock object into one field of a targetObject . I know that targetObject will always have a field with this specific signature.

This all works, I can inject myMockOfSomeObject successfully, and redirect the calls appropriately.

But when the TargetObject class contains other fields like this simple example below, that field gets nulled out and causes null pointer exceptions when I pass requests on to the original object.

Log log = LogFactory.getLog(getClass());

How can I avoid causing other objects to get null values? Especially if the other variables might change from object to object (this code should be generic)?

It seems that spy(..) rather than mock(...) is the correct way to go in this case. Though I haven't yet tested that it injected my mock object, I believe it did.

@RunWith(MockitoJUnitRunner.class)批注添加到测试类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM