2.1 mock 객체 만들기 및 사용

1567 단어
JMockit은 모든 class, interface를 모을 수 있습니다.모크 대상을 필드나 방법의 매개 변수로 설명할 수 있습니다.기본적으로, 모크 대상의 모든 비private 방법 (Object를 제외한 다른 계승 방법 포함) 은 모크에 의해 호출되며, 이 방법에 대한 호출은 기존 코드를 실행하지 않고 J모키 처리에 전달됩니다.mock 스타일의 테스트를 진행하려면 세 가지 절차가 필요합니다:expectation --> 방법 호출 -->verication. 예는 다음과 같습니다.
@Mocked Dependency mockedDependency

@Test
public void test(final @Mocked AnotherDenpendency anotherDependency) {
    new Expectations() {{
        mockedDependency.mockedMethod();
        result = 1;
    }};

    codeUnderTest();

    new Verifications(){{
        anotherDependency.anotherMethod();
        times = 1;
    }};
}

JMockit은 @Mocked 주석의 대상에 의존하여 주입하기 때문에 Expectation, Verication 및 CodeUnderTest에서 직접 모크 대상을 사용할 수 있으며 수동으로 실례화할 필요가 없다.
CodeUnderTest에서 new를 통해 Dependency를 만들고 그 방법을 호출했습니다. JMockit은 자동으로 이 방법 호출을 mock 대상에 옮깁니다.
public class CodeUnderTest {
    public int testMethod() {
        Dependency dependency = new Dependency();
        return dependency.mockMethod();
    }
}
public class Dependency {
    public int mockMethod() {
        return 1;
    }
}

Dependency 클래스의 mockMethod 메서드는 원래 반환 값이 1이고 Expectation에서 반환 값을 2로 설정하면 테스트 과정에서 이 메서드가 2로 반환됩니다.
@Mocked
Dependency dependency;

@Test
public void TestMethod() throws Exception {
    new NonStrictExpectations() {{
        dependency.mockMethod();
        result = 2;
    }};

    CodeUnderTest codeUnderTest = new CodeUnderTest();
    assertEquals(2, codeUnderTest.testMethod());
}

좋은 웹페이지 즐겨찾기