문제

I have same class

class MyCalss{
     final static SomeClass field  = new SomeClass();
     ...
}

I should to mock instance of MyCalss. This mock should contain field like real object.

How can I achieve it?

도움이 되었습니까?

해결책 2

You can use a framework that allows for mocking calls to constructors such as JMockit or Powermock.

Powermock

JMockit

다른 팁

Mocking operates on methods and interfaces, not fields; furthermore, it operates on instance members, not static members. Mockito and Powermock are not the right tools to solve this problem.

Though you can use reflection to set final fields, you're effectively working around your own declaration, and are subject to the limitations and hazards of JLS 17.5.3.

A better design would be to rewrite the method in the system under test to inject its SomeClass dependency:

public void methodUnderTest() {
  methodUnderTest(MyClass.field);
}

/** Package-visible for testing. Test this method instead. */
void methodUnderTest(SomeClass someClass) {
  someClass.firePhotonTorpedoes();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top