2011-06-01 58 views
4

我使用作为的Mockito嘲讽框架。我有一个在这里之情况,我当(abc.method())。thenReturn(值)没有返回值,而是返回null。按捻的Mockito返回空

这里是我的类和测试的样子。

public class foo(){ 
public boolean method(String userName) throws Exception { 
    ClassA request = new ClassA(); 
    request.setAbc(userName);  
    ClassB response = new ClassB(); 
    try { 
     response = stub.callingmethod(request); 
    } catch (Exception e) { 
    } 

    boolean returnVal = response.isXXX(); 
    return returnVal; 
} 

现在follwoing是使用@Mock测试

@Test 
public void testmethod() throws Exception{ 
    //arrange 
    String userName = "UserName"; 
    ClassA request = new ClassA(); 
    ClassB response = new ClassB(); 
    response.setXXX(true); 
    when(stub.callingmethod(request)).thenReturn(response); 
    //act 
    boolean result = fooinstance.lockLogin(userName); 

    //assert 
    assertTrue(result); 
} 

存根使用嘲笑即的Mockito。测试在类foo附近抛出NullPointerException布尔值retrunVal = response.isXXX();

回答

6

参数匹配器用于stub.callingmethod(请求).thenReturn(响应)进行比较以供参考平等。你希望有一个更宽松的匹配,这样我想:

stub.callingmethod(isA(ClassA.class)).thenReturn(response); 
0

确保您ClassA实现了自己的equals,它被正确实施。

+1

我不认为这是正确的修改等方法,以便参数匹配在单元测试工作...... – Kevin 2011-06-01 17:20:02

+1

@Kevin,我同意。但是,如果ClassA是他/她自己的班级,那么应该正确实施。据说,我会选择你的答案,我的:) – 2011-06-01 17:22:08