![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
So, if you think you call a function in your code, and this function returns current time, or a random number... IT'S NOT A FUNCTION. Your code is function of "random number", or "time".
So, if your code is written as something that retrieves this kind of data, to test your code, you should provide that data. Not just today, but try the time, like 10 years from now. As to "random", You provide the randomness. If your code cannot be fixed to behave as a function of those inputs, make your "random stream" or "time stream" not hard-coded, but substitutable. Mockable. And mock it in your tests. MAKE SURE that you don't provide just happy-path data. Provide anything. A sequence of 100 numbers 4 for random. Time that is 10 years from now. Or even 30 yeas from now.
Make sure that your tests don't depend on anything. Because test Must Be Reproducible.
All these things, I know, are obvious to some, and not obvious to others.
So, if your code is written as something that retrieves this kind of data, to test your code, you should provide that data. Not just today, but try the time, like 10 years from now. As to "random", You provide the randomness. If your code cannot be fixed to behave as a function of those inputs, make your "random stream" or "time stream" not hard-coded, but substitutable. Mockable. And mock it in your tests. MAKE SURE that you don't provide just happy-path data. Provide anything. A sequence of 100 numbers 4 for random. Time that is 10 years from now. Or even 30 yeas from now.
Make sure that your tests don't depend on anything. Because test Must Be Reproducible.
All these things, I know, are obvious to some, and not obvious to others.
If you still have questions, ask. But don't argue. Because what I say is math. Unless you have another math (some people do), or another logic (there's plenty of them), please don't argue.
I'd be glad to see how all this changes if logic is e.g. linear.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-29 08:32 pm (UTC)Да, при тестировании с моком одна часть рабочего кода не покрывается.
Но её вроде можно покрыть, добавив тест с настоящим DateTimeCreator.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-29 09:51 pm (UTC)Но если работа с настоящим DateTimeCreator - имплементирована в моке по умолчанию - тогда, действительно, может получиться покрыть рабочий код тестами полностью.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 05:11 pm (UTC)И мы можем протестировать его в таком виде.
А для тестов, которые требуют DateTimeCreator mock, мы втыкаем этот mock в наш сервис вместо настоящего DateTimeCreator-а.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 06:12 pm (UTC)> И мы можем протестировать его в таком виде.
Я именно это и имел ввиду, когда написал "Но если работа с настоящим DateTimeCreator - имплементирована в моке по умолчанию - тогда, действительно, может получиться покрыть рабочий код тестами полностью."
Похоже, разница между нашими утверждениями лишь в том, что вы называете "моком" лишь изменяемую часть, а я называю "моком" весь класс, который включает в себя изменяемую часть.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-31 09:09 am (UTC)Да, похоже на то. А как правильно ?
"Mock" и "mocking" in programming
Date: 2020-08-31 12:18 pm (UTC)Термины "mock" и "mocking" в программировании - несколько неустоявшиеся.
Первые две web pages в списке https://www.google.com/search?q=mock+programming - довольно запутанные:
1) https://en.wikipedia.org/wiki/Mock_object
2) https://stackoverflow.com/questions/2665812/what-is-mocking
Обычно, и Wikipedia и Stackoverflow четко и ясно описывают концепцию, которой они посвящены, но в случае с "mock" и "mocking" - даже в 2020-м году остается довольно путаницы и упущений.
Re: "Mock" и "mocking" in programming
Date: 2020-08-31 08:06 pm (UTC)Re: Is full service test coverage possible with mocks?
Date: 2020-08-31 03:24 pm (UTC)"Partial mocking is not acceptable", сказала мне одна менеджерка в Гугле. Ну, книжек-то она не читала, а нести что-то надо.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 06:58 pm (UTC)> И мы можем протестировать его в таком виде.
Обратите внимание, что обратное - тоже верно: если сервис не включает в себя настоящий DateTimeCreator по умолчанию, то полный test coverage такого кода - невозможен.
Что приводит нас к "best practice" рекомендации о том, как имплементировать моки:
Для того, чтобы повысить test coverage, имплементация мока для рабочего кода - должна быть включена по умолчанию в сервис (чтобы рабочий код, вызывающий этот сервис, не должен был заморачиваться explicit инициализацией mock).
Это, пожалуй, основной вывод из нашей с вами дискуссии о моках.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-31 09:10 am (UTC)Да, можно сделать такой вывод.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-29 10:03 pm (UTC)Вижу, вам уже заморочили голову.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 05:13 pm (UTC)