模拟,模拟和更改Calendar.getIstance() [英] Mockito, mock and change Calendar.getIstance()

查看:82
本文介绍了模拟,模拟和更改Calendar.getIstance()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在被测方法中使用Calendar.getInstance()

I use Calendar.getInstance() inside the Method under test

这是方法

 public List<Object> chechAuth(){
    Calendar from = Calendar.getInstance();
    if(jobService.findJobByCheckAuth(from.getTime(), true).isEmpty()){
        from.add(Calendar.YEAR, -10);
    }
    Calendar to = Calendar.getInstance();
    to.add(Calendar.MONTH, 2);
    
    System.out.println("from: "+from.getTime());
    System.out.println("to: "+to.getTime()); 
    
    return objectDAO.findAuth(from.getTime(), to.getTime());
}

当我使用Calendar = Calendar.getInstance();时返回与2016年7月2日不同的日期

when I use Calendar to = Calendar.getInstance(); it return a date different from July 02 2016

这是我的测试课:

@RunWith(PowerMockRunner.class) 
@PrepareForTest({Calendar.class, ImpServiceTest.class})    
public class ImpServiceTest {

@InjectMocks
private ImpService impService = new ImpServiceImpl();

@Before
public void setup(){
    MockitoAnnotations.initMocks(this);

    Calendar now = Calendar.getInstance();
    now.set(2016, Calendar.JULY, 2 ,0,0,0);
    
    PowerMockito.mockStatic(Calendar.class);
    PowerMockito.when(Calendar.getInstance()).thenReturn(now);
}

@Test
public void methodTEST() throws Exception {
    
     Calendar from = Calendar.getInstance();
     when(jobService.findJobByCheckAuth(eq(now.getTime()), eq(true))).thenReturn(new ArrayList<Job>());

     impService.chechAuth();
  }

此代码打印

发件人:2006年9月2日星期六00:00:00 CEST

From: Sat Sep 02 00:00:00 CEST 2006

收件人:2006年9月2日星期六00:00:00 CEST

To: Sat Sep 02 00:00:00 CEST 2006

我希望第一个Calendar.getInstance()返回

I want that the first Calendar.getInstance() return

CEST 2006年7月2日00:00:00

Sun Jul 02 00:00:00 CEST 2006

第二个

2016年9月2日星期五00:00:00

Fri Sep 02 00:00:00 CEST 2016

一些建议?

推荐答案

您应使用以下注释注释测试类:

You should annotate the test class with:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calendar.class, MyTest.class})

其中 MyTest 是带有测试的类的名称.为了使powermockito正常工作,您需要准备要模拟的类以及目标类的测试.

Where MyTest is the name of the class with tests. For powermockito to work you need to prepare for tests both the class being mocked as well as the target class.

我不确定是否可以为测试类准备测试,因此,如果不起作用,请将日历代码移至其他类.

I'm not sure if it is possible to prepare for tests the test class, so if it doesn't work move the Calendar code to other class.

这篇关于模拟,模拟和更改Calendar.getIstance()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆