How to test a method that depends on another method already tested?

I am working on a method that can be seen as a specialization of another already defined and tested method. Here is an example code to illustrate:

public class ProductService {

    public void addProduct(Product product) {
        //do something
    }

    public void addSpecialProduct(Product product) {
        addProduct(product);
        //do something after
    }

}

I do not want to copy the tests that I have for addProductwhich are already quite complicated. I want, when I define tests for addSpecialProduct, I just make sure that it also calls addProductin the process. If this was due to the joint 2 classes, then it would be easy to comment on the co-author and just check if the target method is called (and if necessary, mute it). However, two methods belong to the same class.

What I am thinking now is to keep track of the object I'm testing, for example:

public void testAddSpecialProduct() {
    //set up code
    ProductService service = spy(new DefaultProductService());    
    service.addSpecialProduct(specialProduct);
    verify(service).addProduct(specialProduct);
    //more tests
}

, - . ?

+4
2

, , . , , . , ( @chrylis ). - .

, , , , . :

1) .

2) , . , , , , .

, , , , . , , , .

0

. , .

public class ProductService {

    @Resource
    private AddProductStrategy normalAddProductStrategy;
    @Resource
    private AddProductStrategy addSpecialProductStrategy;

    public void addProduct(Product product) {
        normalAddProductStrategy.addProduct(product);
    }

    public void addSpecialProduct(Product product) {
        addSpecialProductStrategy.addProduct(product);
    }
}

2 AddProductStrategy. , ProductService.addProduct. , . . - .

0

Source: https://habr.com/ru/post/1652184/


All Articles