Java unit test help

0

I am not sure if a unit test can be implemented on a method whose result is variable in time.

This doubt is based on the fact that I have a method that receives a LocalDate and returns a String with the date in "dd / mm / yyyy" format.

To test it, you created a LocalDate with a specific date and then I get it back, so there's no problem, but do I create a LocalDate for the current date? , how can I know what is the expected result?

What I did was create a second implementation of the initial method, internally different but that receives the same and produces the same output, then I have cross-tested them. The problem would be that both give the same incorrect date ... As a curiosity, I tested the speed of execution of the two implementations and it seems that the new one is 6 times faster ...

    
asked by Orici 29.06.2018 в 19:04
source

1 answer

0
  

I am not sure if a unit test can be implemented on a method whose result is variable in time.

Well, you've done it, so you can.

Even without duplicating the algorithm (we'll talk about that later), you could do the test with the current date and simpler tests (it does not throw an exception, it returns a value that complies with a predetermined regular expression, etc.). That the String itself is not always the same does not mean that it can not be analyzed.

The question is whether it makes sense:

  • Cost: Duplicating the work has a cost.

  • Control: If you decide not to duplicate the algorithm (or simply can not) and do simpler tests (for example, the regular expression), you may miss errors.

  • It does not exempt you from insuring coverage. If you have a special case and on December 25 return "Christmas!", You should pass a value with December 25 to check that it continues to work.

  • For what? Suppose you have a bug that causes problems in 2018; Seven months ago you compiled and the test passed, and now you compile and with your "supertest" you discover it. Very good, but, if your tests happened in 2017, how do you ensure that there is not a bug that will manifest in 2019, not when compiling but in production ? If detecting the bug depends on the input value, your test is not very good.

  • With a unit test you should make sure that you pass enough examples to cover all possible "paths" of your algorithm execution (as in the "Christmas" example, or even error cases such as a null ). Once this is done, if you have done well, you already have a perfect test.

    The mechanism you propose is used for the design of critical systems (control of an airplane, of a nuclear power plant) where there are several systems with different software at run time , so that if one from them begins to give different values can be activated control mechanisms. But for a unit test it is excessive and does not exempt you from doing the tests well to ensure coverage.

        
    answered by 29.06.2018 в 20:22