Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito Spy - stub before calling the constructor

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:

public class MyClass {
    public MyClass() {
         setup();
    }

    public void setup() {

    }
}

The setup method mustn't be called. Well, how do I spy on this method (and stub setup so that it does nothing)?
It works fine with mocking the method but I want to unit test MyClass and so I will need very other method.


The reason why need to stub the setup method so that it does nothing:
I'm programing a Lego robot (lejos) and I put some code in setup that the robot needs to work. However, when I call it outside TinyVM (the VM that is installed on the robot), java crashes since it the VM hasn't been initialized properly (because the tests run on my PC). For unit-testing the setup isn't important.
I can't stub the classes/methods setup calls since some of them are public static final variables.

like image 429
Matt3o12 Avatar asked May 11 '14 21:05

Matt3o12


People also ask

Does Mockito mock call the constructor?

Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.

How do you call a mock method in a constructor?

Faking static methods called in a constructor is possible like any other call. if your constructor is calling a method of its own class, you can fake the call using this API: // Create a mock for class MyClass (Foo is the method called in the constructor) Mock mock = MockManager. Mock<MyClass>(Constructor.

When should a spy be used in Mockito?

A Mockito spy is a partial mock. We can mock a part of the object by stubbing few methods, while real method invocations will be used for the other. By saying so, we can conclude that calling a method on a spy will invoke the actual method, unless we explicitly stub the method, and therefore the term partial mock.

What is stubbing in Mockito?

A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.


3 Answers

To answer your question directly, you cannot use Mockito to stub a method called from the constructor. Mockito needs an instance of the class before you can begin mocking, and you haven't given yourself a way to create an instance for testing.

More generally, as mentioned in Effective Java item 17, you should not call overridable methods from constructors. If you do so, for instance, you could provide an override in a subclass that refers to a final field but that runs before the final field is set. It probably won't get you in trouble here, but it's a bad habit in Java.

Luckily, you can restructure your code to do this very easily:

public class MyClass {
  public MyClass() {
    this(true);
  }

  /** For testing. */
  MyClass(boolean runSetup) {
    if (runSetup) {
      setup();
    }
  }

  /* ... */
}

To make it even more obvious, you can make the one-parameter MyClass constructor private, and provide a public static factory method:

/* ... */
  public static MyClass createForTesting() {
    return new MyClass(false);
  }

  private MyClass(boolean runSetup) {
/* ... */

Though some developers think it is a bad practice to write any code in methods that is used mostly for tests, remember that you are in charge of the design of your code, and tests are one of few consumers you absolutely know you will need to accommodate. Though it's still a good idea to avoid explicit test setup in "production" code, creating extra methods or overloads for the sake of testing will usually make your code cleaner overall and can drastically improve your test coverage and readability.

like image 98
Jeff Bowman Avatar answered Oct 17 '22 10:10

Jeff Bowman


  1. Use PowerMock.

  2. After you've imported the libraries, set it up to manipulate the class you want to mock with the instance method that mustn't be called.

Like so:

@RunWith(PowerMockRunner.class)
@PrepareForTest({<Other classes>, Myclass.class})
  1. Suppress the method at the start of your test.

Like so:

suppress(method(Myclass.class, "setup"));
  1. Customize the behaviour of your setup() method as desired, in your test.

Like so:

doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
           // code here
           return null;
      }
 }).when(Myclass.class, "setup");
like image 12
fragorl Avatar answered Oct 17 '22 09:10

fragorl


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.

like image 11
Matt3o12 Avatar answered Oct 17 '22 10:10

Matt3o12