Reputation: 7849
Suppose I want to create a unit test for a method like this:
public Car map(CarReq request) {
Car car = new Car();
car.setPrice(carReq.getPrice());
car.setColour(carReq.getColour());
car.setType(carReq.getType());
// Other 20 lines like these
return car;
}
I can mock carRequest and tell each method what should return. But that's like not testing anything, as all the method does is getting values from carReq.
I can create a testing carReq object (without mocking) and check that the same values are copied into the output Car object. But that's a lot of work, right?
Isn't there a more intelligent way?
Upvotes: 3
Views: 3335
Reputation: 501
I can create a testing carReq object (without mocking) and check that the same values are copied into the output Car object. But that's a lot of work, right?
It is, but if you really are willing to unit-test this method, you have to do this. Please note that you can use libraries like Orika to perform this kind of dumb field-mapping methods for you. Saves time and code lines :)
Upvotes: 0
Reputation: 53809
You want to test the logic of the method.
Therefore if what the method does is copying the properties of a CarReq
into a Car
, then this is what you should test:
@Test
public void mapTest() {
// Given
CarReq carReq = new CarReq(10000D, ...);
// When
Car car = myClass.map(carReq);
// Then
Assert.assertEquals(car.getPrice(), carReq.getPrice());
// ...
}
Upvotes: 6
Reputation: 272207
I'm not quite sure what the issue is ? Surely since the method takes a request and returns a new Car
, that's precisely what you want to test ? If I was doing it, I would:
Car
fields are what are in the requestCar
?You say that all the method does is call setters/getters, but don't forget that one purpose of a unit test is to assert that the behaviour remains the same going forwards (i.e. you're testing for regressions). If you add additional functionality to this method, and you accidentally break something, the above test will tell you immediately.
Is it a lot of work ? Maybe (perhaps a few mins of copy/paste getter/setter invocations and changing params to be unique per attribute). But it's a lot less work than resolving an issue in production later on.
Upvotes: 0