Home > Software design >  How to build Junit tests for a Comparator.comparing?
How to build Junit tests for a Comparator.comparing?

Time:11-25

After several times trying to solve a sort problem, the only way who worked was using a implementation like this:

List<Product> productsList = new ArrayList<>();

productsList = myRepository.queryResult();

productsList.sort(Comparator.comparing(Product::getPrice));

Basicaly, this code take price attibute as key to sort values in ascending mode.

However, my problem is to build a test for Comparator code.

I had tried to create two objects and sort them to compare but not worked:

@Test
public void getComparisonProducts{
    List<Product> productsList = new ArrayList<>();
    Product product = new Product();
    product.setPrice(11.22);

    productsList.add(product)

    Product product2 = new Product();
    product2.setPrice(22.11);

    productsList.add(product2)

    Comparator<Product> comparator = Comparator.comparing(Product::getPrice);

    productsList.sort(comparator);

    assertEquals(comparator.compare(productsList.get(0), productsList.get(1)), -1);
}

Runing the test, I have this failure:

enter image description here

Some Google's researchs not helped yet.

CodePudding user response:

You have a typo in your code, you are setting the price for product twice, and not at all for product2

CodePudding user response:

Thanks all for trying to help, but a close friend catch the problem. In one of my mocks was with fixed arguments, instead usingarguments matchers. So, was:

when(productRepository.getProducts(111, 2, 3, 4, 555)).thenReturn(productsList);

And now:

when(productRepository.getProducts(anyInt(), anyShort(), anyShort(), anyShort(), anyInt())).thenReturn(productsList);

Appears not to have a correlation but worked. Thanks again!

  • Related