Mockito Spy - stub before calling the constructor

前端 未结 3 2151
悲哀的现实
悲哀的现实 2020-12-24 12:40

I\'m trying to spy on an Object and I want to stub a method that is called by the constructor before the constructor calls it.
My class looks like that:

         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-24 13:25

    Thanks for the suggestions, but it was a little bit too complex.
    I ended up mocking the method by extending the class and overwriting my setup method. This way the default constructor won't call its implementation of setup, it will call the overwritten method instead.
    Here is the code:

    // src/author/MyClass.java
    
    public class MyClass {
        public MyClass() {
            setup();
        }
    
        protected void setup() {
            throw new Exception("I hate unit testing !");
        }
    
        public boolean doesItWork() {
            return true;
        }
    }
    
    // test/author/MyClass.java
    
    public class MyClassTest {
        private class MockedMyClass extends MyClass {
            @Override
            protected void setup() {
    
            }
        }
    
        private MyClass instance;
    
        @Before
        public void setUp() { // Not to be confusing with `MyClass#setup()`!
            instance = new MockedMyClass();
        }
    
        @Test
        public void test_doesItWork() {
            assertTrue(instance.doesItWork());
        }
    
    }
    

    If you don't want MyTest's setup method to do called or overwritten by other subclasses except your test (because other developer might mess things up very badly by using the setup method), just change the visibility to default and only your classes will be able to call setup.


    If there is a simpler way, please answer the question because I'm not 100% content with my solution.

提交回复
热议问题