What are the types of test objects in the context of software development?
sobes.tech AI
Answer from AI
In software development, the following types of test objects are used:
-
Test Double: A general term for any kind of substitute for a real object used in tests.
-
Stub: An object that returns predefined values in response to method calls. Used to control the behavior of dependencies of the tested object.
// Example Stub public class PaymentGatewayStub implements PaymentGateway { @Override public PaymentResult processPayment(PaymentDetails details) { // Always return a successful result return new PaymentResult(true, "Success"); } } -
Spy: A partial double. Wraps a real object, intercepting method calls to check if they were called, how many times, and with what arguments, but can also call real methods.
// Example Spy using Mockito (a popular library for creating test objects) // List<String> listSpy = Mockito.spy(new ArrayList<>()); // listSpy.add("item"); // verify(listSpy).add("item"); // Verify add method call -
Fake: Objects with a working but simplified implementation. For example, an in-memory database instead of a real one.
// Example Fake (simple in-memory DAO implementation) public class ProductDaoFake implements ProductDao { private Map<Long, Product> products = new HashMap<>(); private long nextId = 1; @Override public void save(Product product) { if (product.getId() == null) { product.setId(nextId++); } products.put(product.getId(), product); } @Override public Product findById(Long id) { return products.get(id); } } -
Mock: Objects that not only imitate behavior but also contain predefined expectations regarding method calls. They must "know" how they should be called during the test. If calls do not meet expectations, the test fails.
// Example Mock using Mockito // MockMvc mockMvc = MockMvcBuilders.standaloneSetup(myController).build(); // when(myService.getData()).thenReturn("test data"); // Expectation for getData call // mockMvc.perform(get("/api/data")) // .andExpect(status().isOk()) // .andExpect(content().string("test data")); // Verify result // verify(myService).getData(); // Check that getData was called
The main difference between them lies in the purpose of use and the level of imitation complexity:
| Type | Purpose | Behavior | Call Verification |
|---|---|---|---|
| Stub | Provide predefined responses | Fixed responses | No |
| Spy | Verify calls to real object methods | Imitates part of real object behavior (+ real methods) | Yes |
| Fake | Simplify dependency with working logic | Simplified but working logic | Usually no |
| Mock | Verify interaction between objects | Predefined call expectations | Yes |