問題描述
我有一個需要測試的類A
.以下是A
的定義:
I have a class A
that needs to the tested. The following is the definition of A
:
public class A {
public void methodOne(int argument) {
//some operations
methodTwo(int argument);
//some operations
}
private void methodTwo(int argument) {
DateTime dateTime = new DateTime();
//use dateTime to perform some operations
}
}
并且基于 dateTime
值,一些數(shù)據(jù)將被操作,從數(shù)據(jù)庫中檢索.對于此數(shù)據(jù)庫,這些值通過 JSON 文件進行持久化.
And based on the dateTime
value some data is to be manipulated, retrieved from the database. For this database, the values are persisted via a JSON file.
這使事情變得復(fù)雜.我需要的是在測試時將 dateTime
設(shè)置為某個特定日期.有沒有辦法可以使用 mockito 模擬局部變量的值?
This complicates things. What I need is to set the dateTime
to some specific date while it is being tested. Is there a way I can mock a local variable's value using mockito?
推薦答案
你不能模擬一個局部變量.但是,您可以做的是將其創(chuàng)建提取到 protected
方法并 spy
它:
You cannot mock a local variable. What you could do, however, is extract its creation to a protected
method and spy
it:
public class A {
public void methodOne(int argument) {
//some operations
methodTwo(int argument);
//some operations
}
private void methodTwo(int argument) {
DateTime dateTime = createDateTime();
//use dateTime to perform some operations
}
protected DateTime createDateTime() {
return new DateTime();
}
}
public class ATest {
@Test
public void testMethodOne() {
DateTime dt = new DateTime (/* some known parameters... */);
A a = Mockito.spy(new A());
doReturn(dt).when(a).createDateTime();
int arg = 0; // Or some meaningful value...
a.methodOne(arg);
// assert the result
}
這篇關(guān)于使用 Mockito 模擬方法的局部變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!