Mockito mock calling real method implementation when attempting to stub package protected method

后端 未结 2 1137

I\'m trying to stub a method using Mockito 1.8.5, but doing so calls the real method implementation (with \"\" as parm values) which throws an exception.

pac         


        
2条回答
  •  渐次进展
    2020-12-17 08:42

    I disagree with the accepted response.

    I think, you have to provide more details on your environment. I can't reproduce your problem. I write the following code in a maven project :

    package background.internal; //located in src/main/java
    
    public class FileAttachmentContainer {
        String moveAttachment(String arg1, String arg2, String arg3) {
            throw new IllegalStateException();
        }
    
        String getPersistedValue(Context context) {
            throw new IllegalStateException();
        }
    }
    

    and

    package background.internal;
    
    public class AttachmentMoveStep {
    
        private FileAttachmentContainer file;
    
        public AttachmentMoveStep(FileAttachmentContainer file) {
            this.file = file;
        }
    
        public Action advance(double acceleration, Context context) {
            String attachmentValue = file.getPersistedValue(context);
            file.moveAttachment(attachmentValue, "attachment", context.getUserName());
            return Action.done;
        }
    }
    

    and the following test pass

    package background.internal; //located in src/test/java
    
    import static org.junit.Assert.assertEquals;
    import static org.mockito.Matchers.anyString;
    import static org.mockito.Mockito.doReturn;
    import static org.mockito.Mockito.mock;
    
    import org.junit.Test;
    
    public class MoveStepTest {
    
        @Test
        public void testMoveUpdate() {
            String returnValue = "value";
            FileAttachmentContainer file = mock(FileAttachmentContainer.class);
            doReturn(returnValue).when(file).moveAttachment(anyString(), anyString(), anyString());
            //this also works
            //when(file.moveAttachment(anyString(), anyString(), anyString())).thenReturn(returnValue);
    
            AttachmentMoveStep move = new AttachmentMoveStep(file);
            Action moveResult = move.advance(1, mock(Context.class));
            assertEquals(Action.done, moveResult);
        }
    }
    

    My project use the following dependencies :

    • jdk1.7.0_05
    • junit-4.10.jar
    • mockito-all-1.9.0.jar
    • javassist-3.16.1-GA.jar
    • objenesis-1.2.jar
    • hamcrest-core-1.1.jar

提交回复
热议问题