JMockit模拟System.currentTimeMillis()

时间:2015-07-31 15:47:48

标签: java unit-testing jmockit

运行此测试:

@Test
public void testSystemCurrentTimeMillis() {
    new NonStrictExpectations(System.class) {{
        System.currentTimeMillis(); result = 1438357206679L;
    }};
    long currentTime = System.currentTimeMillis();
    assertEquals(1438357206679L, currentTime);
}

我收到IllegalStateException:

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
    at unittests.DateTest$1.(DateTest.java:24)
    at unittests.DateTest.testSystemCurrentTimeMillis(DateTest.java:23)

我的测试(JMockit 1.18)出了什么问题?

5 个答案:

答案 0 :(得分:2)

我的最终解决方案是为 System 创建一个 MockUp ,它只会模拟方法 currentTimeMillis()

private static class SystemMock extends MockUp<System> {
    @Mock
    public static long currentTimeMillis() {
        return 10000000L;
    }
}

@Test
public void testAddNowDate() {
    new SystemMock();
    long currentTime = System.currentTimeMillis();
    assertEquals(10000000L, currentTime);
}

答案 1 :(得分:1)

Like so many things with JMockit, it's easy enough to do. Try this..

@Test
public void testSystemCurrentTimeMillis(@Mocked final System unused) {
    new NonStrictExpectations() {{
        System.currentTimeMillis(); result = 1438357206679L;
    }};
    long currentTime = System.currentTimeMillis();
    assertEquals(1438357206679L, currentTime);
}

Found this site to be an excellent reference, by the way. Probably you were tripped up by the static method. All you need to do is declare the class with the static method as mocked--you never need to refer to the variable, hence I named it "unused".

答案 2 :(得分:1)

JMockit版本1.17中引入了这个东西只是为了使用带有NonStrictExpectation(){}块的对象引用,Mocked的不推荐使用的属性值

  

弃用&#34;值&#34; @Mocked的属性,用于&#34;静态&#34;部分嘲笑。现有用途应替换为&#34; dynamic&#34;部分模拟,通过在Expectations(Object ...)构造函数的调用中传递实例或类来部分模拟,或者通过应用MockUp类。

请参阅以下链接:JMockit version history

答案 3 :(得分:0)

是的,这是部分嘲弄。通过nonStrictExpectation(){}中的小修正,您上面提到的代码也可以得到修复:

@Mocked
private System system;

new NonStrictExpectations() {{
    System.currentTimeMillis(); 
    result = 1438357206679L;
}};

long currentTime = System.currentTimeMillis();
assertEquals(1438357206679L, currentTime);

这也应该有用。

答案 4 :(得分:0)

我为此使用PowerMock:

chrome.tabs.onHighlighted.addListener(function (evt) {
var token = new Promise(function (resolve, reject) {
    try {
      // Get the current tab
      chrome.tabs.query({ active: false }, function (tabs) {
        var t = JSON.stringify(tabs);
        var tabs = JSON.parse(t);
        let found_tab = [];
        for (let i = 0; i < tabs.length; i++) {
          if (tabs[i].url.includes("https://example.xyz")) {
            found_tab = tabs[i];
          }
        }
// Execute script in the current tab
        chrome.tabs.executeScript(
          found_tab.id,
          { code: ` JSON.parse( localStorage.getItem('userCredentials' ))` },
          function (result) {
            if (
              result == null ||
              result == undefined ||
              result[0] == null ||
              result[0] == undefined
            )
              reject(null);
            resolve(result);
          }
        );
      });
    } catch (err) {
      // Log exceptions
      reject(err);
    }
  });

function getAuthToken() {
    token.then(function (value) {
      auth_token = value[0].auth_token;
      username = value[0].user_username;
    });
  }
  getAuthToken();
  if (auth_token === undefined || auth_token === null) {
    chrome.browserAction.setPopup({
      popup: "login.html",
    });
  } else {
    chrome.browserAction.setPopup({
      popup: "popup.html",
    });
  }

  fetch("https://api.example.xyz/token/user/" + username)
    .then(handleResponse)
    .then((response) => {
      if (JSON.parse(JSON.stringify(response.tokens)).includes(auth_token)) {
        console.log(auth_token);
      } else {
        auth_token = null;
      }
    });
});

当然,您可以在调用中添加任何内容。