So I am still having trouble with the usage of Mockito. So let's assume I have following class (Please ignore the logic, or structure of it, it's just a short example I created from another class, with different names and so on.) :
public class Restaurant(
@Autowired
private CustomerService customerService;
private CustomerInputData updateCustomer(CustomerInputData inputData){
final String customerId = inputData.getID();
final Customer customer = customerService.getCustomerById(customerID);
if(customer.getAddress() != null){
inputData.setCustomerName(customer.getCustomerName());
inputData.setCustomerCity(customer.getCustomerCity);
inputData.setCustomerLanguage(customer.getLanguage);
}
return inputData
}
}
So my understanding of Unit-Tests is, to isolate all dependencies. Here I would have the Customer-class and the Customer-Service.
So to write a test-class, I would currently do following:
public class RestaurantTest()
{
@Mock(name="customerService");
private CustomerService customerService;
@InjectMocks
private Restaurant classUnderTest;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void updateCustomer_WithValidInput_ShouldReturnUpdatedInput(){
//Some Mocking first
final String customerId = "customerId";
final Customer customer = mock(Customer.class);
final final CustomerInputData = mock(CustomerInputData.class);
doReturn(customer).when(customerService.getCustomerById(any(String.class)));
doReturn(customerId).when(inputData.getId());
doReturn("address").when(customer.getAddress());
doReturn("Name").when(customer.getName());
doReturn("City").when(customer.getCity());
doReturn("Language").when(customer.getLanguage());
doNothing().when(inputData).setCustomerName(any(String.class));
doNothing().when(inputData).setCustomerCity(any(String.class));
doNothing().when(inputData).setCustomerLanguage(any(String.class));
verify(customer.getAddress(), atLeastOnce());
verify(customer.getName(), atLeastOnce());
//and so on...
verify(inputData, atLeastOnce()).setCustomerName(eq("Name"));
verify(inputData, atLeastOnce()).setCustomerCity(eq("City"));
verify(inputData, atLeastOnce()).setCustomerLanguage(eq("Language");
}
}
So currently I have no Assert, I only check if the right methods get called. The reason, why I try to do this like this, and not let the Test-class call the setter/getter is because of isolation. Let's assume inputData.setCustomerCity is broken, my test would fail. So it is depending on the CustomerInputData-Class.
Now how do I approach these getter and setters, what is the best practice?
Do I have not understood Mockito good enough? When I use mock(), can I then just use the setter-methods and gethods, and don't need to worry about using doReturns and so on?
I know it is a whitebox-test, I know the methods and what's going on.
Aucun commentaire:
Enregistrer un commentaire