2014-09-01 42 views
1

我在我的主题这段代码在测试:列表中的一个元素惩戒方法

public class Widget { 
    private Set<Thing> things; 
    public Set<Thing> getThings() { return things; } 
    public void setThings(Set<Thing> things) { this.things = things; } 

    public void performAction(PerformingVisitor performer) { 
     for (Thing thing: getThings()) 
     { 
      thing.perform(performer); 
     } 
    } 
} 

我的JUnit /的Mockito测试看起来像:

@RunWith(MockitoJUnitRunner.class) 
public class WidgetTest { 
    @Mock private PerformingVisitor performer; 
    @Mock private Thing thing; 
    @InjectMocks private Widget widget; 

    @Before 
    public void setUp() throws Exception { 
     Set<Thing> things = new HashSet<Thing>(); 
     things.add(thing); 
     widget.setThings(things); 

     MockitoAnnotations.initMocks(this); 
    } 

    @Test 
    public void shouldPerformThing() { 
     Mockito.when(thing.perform(Mockito.any(PerformingVisitor.class))).thenReturn(true); 

     widget.performAction(performer); 

     Mockito.verify(thing).perform(Mockito.any(PerformingVisitor.class)); 
    } 
} 

然而,这给了我错误:

Wanted but not invoked: 
thing.perform(<any>); 
    -> at com.myclass.ThingTest.shouldPerformThing(WidgetTest.java:132) 

我验证过的代码进入for循环,应该调用实际thing.perform(performer);一行,但我的模拟似乎没有录制电话。

回答

1

我想你在模拟注射之前需要initMocks

你能试着改变你的设置方法如下:

@Before 
    public void setUp() throws Exception { 
     MockitoAnnotations.initMocks(this); 
     Set<Thing> things = new HashSet<Thing>(); 
     things.add(thing); 
     widget.setThings(things); 
    } 

希望工程

+0

Doh!是的,这是一个愚蠢的错误。谢谢。 – 2014-09-01 07:26:20

+0

它的作品,但声明'MockitoAnnotations.initMocks(this);'是无用的。 – gontard 2014-09-01 07:30:19

1

MockitoJUnitRunnerjavadoc

Initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary.

所以,如果你删除

MockitoAnnotations.initMocks(this) 

从您的setUp方法,测试通过。