Mockito:调用方法里面的方法

use*_*163 2 mockito

我在其中有以下类和方法

public class A extends B implements C{


public void validateTicketGrantingTicket(final TicketGrantingTicket ticketGrantingTicket) throws InvalidTicketException {

    if (ticketGrantingTicket != null)
    {
        if (!ticketGrantingTicket.getHostDomain().equalsIgnoreCase(getServerName()))
        {
            throw new InvalidTicketException();
        }
    }
}


public String getServerName()
{
    String serverName = "";
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    if (request != null)
    {
        serverName = request.getServerName().toLowerCase();
    }

    return serverName;
}
}
Run Code Online (Sandbox Code Playgroud)

现在我正在写ATest课并嘲笑A班.

public class ATest {
private A a;

@Before
public void init(){

    A = mock(A.class);

    when(A.getServerName()).thenReturn("phoenix.edu.abc");      
}


@Test
public void validateTicketGrantingTicketTest() throws  InvalidTicketException{  
    a = new A();
    ticketGrantingTicket = new   
    TicketGrantingTicketImpl("test",testUtils.getAuthentication(), new 
    NeverExpiresExpirationPolicy());

    a.validateTicketGrantingTicket(ticketGrantingTicket);
}
Run Code Online (Sandbox Code Playgroud)

Mock对象给了我getServerName()方法的空指针异常而不是字符串"phoenix.edu.abc"

mat*_*sev 7

通过调用a = new A();测试方法,可以创建A的新实例,并且对init()方法中创建的模拟A实例的引用将丢失.因此,A的"真实" getServerName()方法实现将被调用,而不是你所嘲笑的那个.

你遇到的另一个问题是你试图同时模拟和测试同一个类.一方面你正在测试validateTicketGrantingTicket(),但同时你在嘲笑getServerName().您可以使用spy()而不是使用spy来解决此问题mock(),但最好将代码重构为两个单独的类.