2017-08-04 60 views
0

我在我的代码中有2 constructor。一个是默认的构造函数(无参数),另一个是参数化的构造函数。为什么我们不能使用Mockito为参数化构造函数创建间谍

我想间谍参数化构造函数注入模拟对象作为我的junit的依赖项。

public RegDao(){ 
//original object instantiation here 
Notification .... 
EntryService ..... 
} 

public RegDao(Notification notification , EntryService entry) { 
// initialize here 
} 

we have something like below : 
RegDao dao = Mockito.spy(RegDao.class); 

但是,我们有什么事情,我可以在构造注入嘲笑对象,并窥探它?

回答

0

听起来像你可能错过了依赖注入解决方案。 Mockito非常适合与你的DI合作注入模拟。例如,您可以使用CDI,在您的测试中注释您的NotificationEntryService成员@Inject,声明@Mock s,然后让Mockito将这些注入RegDao进行测试。

下面是测试的工作样机,我认为你想运行:

import static org.junit.Assert.assertEquals; 

import javax.inject.Inject; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.mockito.InjectMocks; 
import org.mockito.Mock; 
import org.mockito.Spy; 
import org.mockito.runners.MockitoJUnitRunner; 

@RunWith(MockitoJUnitRunner.class) 
public class MockitoSpyInjection { 
    static class Notification { } 
    static class EntryService { } 
    static class RegDao { 
     @Inject 
     Notification foo; 

     @Inject 
     EntryService bar; 

     public RegDao() { 
     } 

     public RegDao(Notification foo, EntryService bar) { 
      this.foo = foo; 
      this.bar = bar; 
     } 

     public Notification getFoo() { 
      return foo; 
     } 

     public EntryService getBar() { 
      return bar; 
     } 

    } 


    @Mock 
    Notification foo; 

    @Mock 
    EntryService bar; 

    @Spy 
    @InjectMocks 
    RegDao dao; 

    @Test 
    public void test() { 
     assertEquals(foo, dao.getFoo()); 
     assertEquals(bar, dao.getBar()); 
    } 
} 
相关问题