Search code examples
javajmockitjmock

JMockit Dependency Constructor


I am looking to mock out a Domain Dependency while I test a Service Class, using JMockit. The problem is, that the Domain object is instantiated in one of the Service's methods, and the Domain constructor used, has parameters.

Domain Class:

package com.example;
public class DomainClass {
  String str;
  public DomainClass(String s) {
    str=s;
  }
  public String domainMethod() {
    return str;
  }
}

Service Class

package com.example;
public class ServiceClass {
  public String serviceMethod() {
    return new DomainClass("original").domainMethod();
  }
}

How do I mock out the DomainClass that the ServiceClass is using?

Note: I am not looking to change the Domain or Service classes. (I realize that this code is is trivial and could be written better, but it is just a simple example of more complex code.)

Test Class (Final Answer)

package com.example;
import org.testng.*;
import org.testng.annotations.*;
import mockit.*;
public class TestClass {
  @Mocked DomainClass domainClass;
  @Test
  public void testMethod() {
      new Expectations() {{
          new DomainClass("original").domainMethod(); result = "dummy";
      }};
      String ss = new ServiceClass().serviceMethod();
      System.out.println(ss);
      Assert.assertEquals(ss, "dummy");
  }
}

Solution

  • The JMockit documentation should answer that.

    Anyway, to mock a class, simply use @Mocked DomainClass (as mock field or test method parameter).

    BTW, having new DomainClass("original").domainMethod() is not "bad design" (on the contrary, turning it into a singleton - injected or not - would be). However, mocking such classes may very well be a bad idea; always prefer not mocking.