0

I would like to now, if it is possible to mock a class like

public class MyClass{
   ...
}

Our business logic create this object with new myClass() somewhere in the code and therefore I don't have access to the created object to mock those methods. Is there a way to replace the whole class or to overwrite those methods. I'm using mockito and I only found examples to do this like

@Test
public void myTest{
    MyClass myClass = Mockito.mock(MyClass.class);
    Mockito.when(myClass.myMethod()).thenReturn("hello World");
    ...
}

We can't use PowerMock because it isn't compatible with our test environment.

Any suggestions are welcome.

Simon Schüpbach
  • 2,625
  • 2
  • 13
  • 26

2 Answers2

0

Sorry, i see only two hardcore solutions:

Make Powermock working by using PowerMockRule and PowerMock Rule Agent: Getting javassist not found with PowerMock and PowerRule in Junit with Mockito

or

Use Java Reflection to set the mocked object to MyClass: Is it possible in Java to access private fields via reflection

Community
  • 1
  • 1
tak3shi
  • 2,305
  • 1
  • 20
  • 33
0

I found a passable way to achieve my requirement.

I converted MyClass to a bean, just add annotation @Dependent.

@Dependent
public class MyClass{
   public Integer someMethod(){
       return 100;
   }
}

I use MyClass in business logic like that

public class BusinessClass{
    @Inject
    MyClass myClass

    public Integer doSomething(){
        return myClass.someMethod();
    }
}

After this change I'm able to mock the class in my test with annotation @Specializes

@Specializes
@Dependent
public class MyClassMock extends MyClass
{
    @Override
    public Integer someMethod(){
        return 23; // return my mocked value
    }
}

MyClass will be automatically replaced with MyClassMock in testenvironment.

Simon Schüpbach
  • 2,625
  • 2
  • 13
  • 26