vendredi 5 février 2016

Unit Testing Null Pointer Exception

I'm currently trying to complete a piece of Test Driven Development coursework and have ran into a problem with the following code:

package stockInformation;

public class StockInformation {

String companyName;

public String getCompanyName() {
    return companyName;
}

private WebService webService;

// Constructor
public StockInformation(int userID) {

    if (webService.authenticate(userID)){
        //Do nothing
    } else {
        companyName = "Not Allowed";
    }
}
}

(The if-else is done poorly on purpose so that I can refactor it later on in the assignment)

Web Service which is 'being developed by another team' so needs to be mocked package stockInformation;

public interface WebService {

public boolean authenticate(int userID);

}

Test Class

package stockInformation;

import org.junit.Before;
import org.junit.Test;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

public class StockInformationTest {

WebService mockWebService;
StockInformation si;

@Before
public void setUp() throws Exception {
    mockWebService = createMock(WebService.class);
}

@Test
public void testUserIdAuthentication() {
    int userID = -2;
    si = new StockInformation(userID);
    expect(mockWebService.authenticate(userID)).andReturn(false);
    replay(mockWebService);
    assertEquals("Not Allowed", si.getCompanyName());
    verify(mockWebService); 
}

}

When I run the unit test I get a NullPonterException at:

if (webService.authenticate(userID)){

and

si = new StockInformation(userID);

I want the unit test to pass :) Any help appreciated.

Aucun commentaire:

Enregistrer un commentaire