2
\$\begingroup\$

Is this good approach, to mock some domain object, for example javax.persistence.Entity, or DTO (data transfer object)? Below is simplified source code:

@Entity
public class Entity {
    @Id
    private int id;
    private String name;
    // getters and setters
}

//Spring repo for example
@Repository
public interface EntityRepo {
    Entity findOne(int id);
}

@Component
public class SomeProcessing {
    private EntityRepo entityRepo;

    public SomeProcessing(int id) {
        entityRepo.findOne(id);
        //some logic which would be tested
    }

}

@RunWith(MockitoJUnitRunner.class)
public class SomeProcessingTest {
    @Mock
    private EntityRepo entityRepoMock;
    @Mock
    private Entity entityMock; //it this ok? Or better not to mock it and use just "new Entity()" with getters/setters

    @Test(){
        given(entityMock.getName()).willReturn("text");
        given(entityRepoMock.findOne(anyInt())).willReturn(entityMock);

        //here is other testing stuff
    }
}

Is my understanding correct, that this is refer to Classical vs Mockist testing? Or, there is any other issues not to use mocked Entity or DTO objects?

\$\endgroup\$

closed as off-topic by Vogel612, forsvarir, Graipher, janos Mar 21 '17 at 12:52

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ As per my understanding there are two cases where mocks are not required: collections and DTOs. But You should create special Bulders that can create DTOs for all your tests with default values and have methods to change certain values for a certain test. \$\endgroup\$ – Timothy Truckle Mar 20 '17 at 15:26
  • \$\begingroup\$ I support mocking DTOs. The purpose is not to test the DTO but to facilitate isolating code and triggering code paths in the SUT. It also reduces boilerplate test code because you change a DTOs field value when you need to execute a different code path without instantiating it, for the nth time, a new object. \$\endgroup\$ – nullsteph Oct 1 '18 at 1:46
0
\$\begingroup\$

You don't need to mock the Entity/DTO object . Good practice is to create a new instance of DTO object and set data using setters .

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.