2009-09-08 4 views
0

클래스에 Spring Application Ctx를로드하려는 정적 변수가있는 단위 테스트 문제가 있습니다.JMock을 사용하여 Java에서 정적 변수를 모의하는 방법

이 클래스는 Bean Factory에서 나오지 않으며이 사실을 변경할 수 없습니다.

static ApplicationContext applicationContext = ...; 

이 잘 작동하지만 JMock에 어려운, 얻거나, 내가 방법을 알고 내가 할 수있는 봄 CTX가 시작하고 싶어 할 때까지하지 않습니다. 단위 테스트 상황에 적합하지 않습니다.

누구나 알고있는 문제가 있습니까? 정적 변수를 원하는대로 변경할 수 있습니다.

감사합니다.

답변

1

해결했습니다.

정말 간단했습니다. 저스티 드는 내 정적을 수업에서 랩핑해서 내가 조롱 할 수 있어야합니다.

public class ApplicationContextHolder implements ApplicationContextHoldable { 

    protected static ApplicationContext applicationContext = ...; 

    @Override 
    public ApplicationContext getApplicationContext() { 
     return ApplicationContextHolder.applicationContext; 
    } 

} 
0

니스. 아이러니 한 가지 봄이 싱글 톤을 관리하고 좋은 것을 것을, 그래서 정적 변수의 필요성 :

+0

사실이지만 현실 세계에서는 항상이 옵션이있는 것은 아닙니다. :) – JamesC

0

당신은/개인 정적 필드

import static mockit.Deencapsulation.setField; 
    //Test method 
    public void testSample { 
     setField(Sample.class,"isPrivate",true); 
     setField(Sample.class,"isStatic",true); 
    } 

    private class Sample { 
     private boolean isPrivate = false; 
     private boolean isStatic = false; 

    } 
을 설정 JMock API를 기반으로 반사를 사용할 수 없을한다
관련 문제