49

現在の時刻を使用して計算を行う関数があります。私はmockitoを使ってモックしたいと思います。

テストしたいクラスの例:

public class ClassToTest {
    public long getDoubleTime(){
        return new Date().getTime()*2;
    }
}

次のようなものが欲しいです:

@Test
public void testDoubleTime(){
   mockDateSomeHow(Date.class).when(getTime()).return(30);
   assertEquals(60,new ClassToTest().getDoubleTime());
}

それを嘲笑することは可能ですか?テストのために「テスト済み」コードを変更したくありません。

4

7 に答える 7

66

正しいことは、コードを再構築して、以下に示すようにテストしやすくすることです。コードを再構築して Date への直接的な依存関係を削除すると、通常のランタイムとテスト ランタイムに異なる実装を挿入できるようになります。

interface DateTime {
    Date getDate();
}

class DateTimeImpl implements DateTime {
    @Override
    public Date getDate() {
       return new Date();
    }
}

class MyClass {

    private final DateTime dateTime;
    // inject your Mock DateTime when testing other wise inject DateTimeImpl

    public MyClass(final DateTime dateTime) {
        this.dateTime = dateTime;
    }

    public long getDoubleTime(){
        return dateTime.getDate().getTime()*2;
    }
}

public class MyClassTest {
    private MyClass myClassTest;

    @Before
    public void setUp() {
        final Date date = Mockito.mock(Date.class);
        Mockito.when(date.getTime()).thenReturn(30L);

        final DateTime dt = Mockito.mock(DateTime.class);
        Mockito.when(dt.getDate()).thenReturn(date);

        myClassTest = new MyClass(dt);
    }

    @Test
    public void someTest() {
        final long doubleTime = myClassTest.getDoubleTime();
        assertEquals(60, doubleTime);
    }
}
于 2012-08-09T16:34:57.767 に答える
26

リファクタリングできないレガシー コードがあり、影響を与えたくない場合は、 と を使用してSystem.currentTimeMillis()これを試してください。PowermockPowerMockito

//note the static import
import static org.powermock.api.mockito.PowerMockito.whenNew;

@PrepareForTest({ LegacyClassA.class, LegacyClassB.class })

@Before
public void setUp() throws Exception {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("PST"));

    Date NOW = sdf.parse("2015-05-23 00:00:00");

    // everytime we call new Date() inside a method of any class
    // declared in @PrepareForTest we will get the NOW instance 
    whenNew(Date.class).withNoArguments().thenReturn(NOW);

}

public class LegacyClassA {
  public Date getSomeDate() {
     return new Date(); //returns NOW
  }
}
于 2015-05-23T17:06:16.770 に答える
6

これは、静的メソッドをモックできるように Mockito を拡張するPowerMockを使用して行うことができます。その後、最終的に時間を取得する場所であるモックを作成できます。System.currentTimeMillis()new Date()

できます。すべきかどうかについて意見を述べるつもりはありません。

于 2012-08-09T20:13:29.390 に答える
1

質問に直接答えることはありませんが、根本的な問題 (再現可能なテストがある) を解決する可能性がある 1 つのアプローチは、Dateテストのパラメーターとして を許可し、デフォルトの日付にデリゲートを追加することです。

そのようです

public class ClassToTest {

    public long getDoubleTime() {
      return getDoubleTime(new Date());
    }

    long getDoubleTime(Date date) {  // package visibility for tests
      return date.getTime() * 2;
    }
}

本番コードでは、 を使用getDoubleTime()してテストしgetDoubleTime(Date date)ます。

于 2016-07-05T16:49:02.920 に答える
-1
Date now = new Date();    
now.set(2018, Calendar.FEBRUARY, 15, 1, 0); // set date to 2018-02-15
//set current time to 2018-02-15
mockCurrentTime(now.getTimeInMillis());

private void mockCurrentTime(long currTimeUTC) throws Exception {
    // mock new dates with current time
    PowerMockito.mockStatic(Date.class);
    PowerMockito.whenNew(Date.class).withNoArguments().thenAnswer(new Answer<Date>() {

        @Override
        public Date answer(InvocationOnMock invocation) throws Throwable {
            return new Date(currTimeUTC);
        }
    });

    //do not mock creation of specific dates
    PowerMockito.whenNew(Date.class).withArguments(anyLong()).thenAnswer(new Answer<Date>() {

        @Override
        public Date answer(InvocationOnMock invocation) throws Throwable {
            return new Date((long) invocation.getArguments()[0]);
        }
    });

    // mock new calendars created with time zone
    PowerMockito.mockStatic(Calendar.class);
    Mockito.when(Calendar.getInstance(any(TimeZone.class))).thenAnswer(new Answer<Calendar>() {
        @Override
        public Calendar answer(InvocationOnMock invocation) throws Throwable {
            TimeZone tz = invocation.getArgumentAt(0, TimeZone.class);
            Calendar cal = Calendar.getInstance(tz);
            cal.setTimeInMillis(currTimeUTC);
            return cal;
        }
    });
}
于 2018-04-10T10:14:29.177 に答える