UFO ET IT

Mockito : 모의 비공개 필드 초기화

ufoet 2020. 12. 6. 22:24
반응형

Mockito : 모의 비공개 필드 초기화


인라인으로 초기화되는 필드 변수를 어떻게 모의 할 수 있습니까?

예 :

class Test {
    private Person person = new Person();
    ...
    public void testMethod() {
        person.someMethod();
        ...
    }
}

여기에서는 test # testMethod 메서드를 테스트하는 동안 person.someMethod () 를 조롱하고 싶습니다 .

나는 사람 변수의 초기화를 모의해야합니다. 단서가 있습니까?

편집 : Person 클래스를 수정할 수 없습니다.


Mockito에는 일부 리플렉션 보일러 플레이트 코드를 저장하는 도우미 클래스가 있습니다.

import org.mockito.internal.util.reflection.Whitebox;

//...

@Mock
private Person mockedPerson;
private Test underTest;

// ...

@Test
public void testMethod() {
    Whitebox.setInternalState(underTest, "person", mockedPerson);
    // ...
}

업데이트 : 불행하게도 mockito 팀은 결정 클래스를 제거하는 또 다른 라이브러리 (예를 들어, 사용, 다시 자신의 반사 상용구 코드를 작성하는 그래서 Mockito 2에 아파치 코 몬즈 랭을 , 또는 단순히 붙잡을) 화이트 박스 클래스 (그것이 MIT 라이센스 ).

업데이트 2 : JUnit 5는 유용 할 수있는 자체 ReflectionSupportAnnotationSupport 클래스 함께 제공되며 또 다른 라이브러리를 가져 오지 않아도됩니다 .


파티에 꽤 늦었지만 여기에서 쳐서 친구의 도움을 받았습니다. 문제는 PowerMock을 사용하지 않는 것이 었습니다. 이것은 최신 버전의 Mockito에서 작동합니다.

Mockito는 이것과 함께 제공됩니다 org.mockito.internal.util.reflection.FieldSetter.

기본적으로 리플렉션을 사용하여 개인 필드를 수정하는 데 도움이됩니다.

이것이 당신이 그것을 사용하는 방법입니다-

@Mock
private Person mockedPerson;
private Test underTest;

// ...

@Test
public void testMethod() {
    FieldSetter.setField(underTest, underTest.getClass().getDeclaredField("person"), mockedPerson);
    // ...
    verify(mockedPerson).someMethod();

}

이렇게하면 모의 객체를 전달한 다음 나중에 확인할 수 있습니다.

참고:

https://www.codota.com/code/java/methods/org.mockito.internal.util.reflection.FieldSetter/set


나는 이미 여기에 게시하는 것을 잊은이 문제에 대한 해결책을 찾았습니다.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {

@Mock
Person person;

@Test
public void testPrintName() throws Exception {
    PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
    Test test= new Test();
    test.testMethod();
    }
}

이 솔루션의 핵심 사항은 다음과 같습니다.

  1. PowerMockRunner로 테스트 케이스 실행 : @RunWith(PowerMockRunner.class)

  2. Instruct Powermock to prepare Test.class for manipulation of private fields: @PrepareForTest({ Test.class })

  3. And finally mock the constructor for Person class:

    PowerMockito.mockStatic(Person.class); PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);


In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils

 ReflectionTestUtils.setField(testObject, "person", mockedPerson);

Following code can be used to initialize mapper in REST client mock. The mapper field is private and needs to be set during unit test setup.

import org.mockito.internal.util.reflection.FieldSetter;

new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());

Using @Jarda's guide you can define this if you need to set the variable the same value for all tests:

@Before
public void setClientMapper() throws NoSuchFieldException, SecurityException{
    FieldSetter.setField(client, client.getClass().getDeclaredField("mapper"), new Mapper());
}

But beware that setting private values to be different should be handled with care. If they are private are for some reason.

Example, I use it, for example, to change the wait time of a sleep in the unit tests. In real examples I want to sleep for 10 seconds but in unit-test I'm satisfied if it's immediate. In integration tests you should test the real value.

참고URL : https://stackoverflow.com/questions/36173947/mockito-mock-private-field-initialization

반응형