En este artículo, vamos a centrarnos en hablar más detalladamente sobre las pruebas Unitarias. Para poder seguir completamente este artículo, es muy recomendable el haber leído nuestro artículo de Introducción a las Pruebas de Software (Testing software). En el artículo anterior, expusimos en términos generales, las principales pruebas que podemos realizar para un desarrollo del software.
Ampliando lo que hablemos en dicho artículo, descartar la realización de pruebas unitarias debido a una carga de trabajo elevada, a falta de tiempo, a que el cliente no las a solicitó, a causa de falta de conocimiento, o el motivo que sea, es un grave error.
Las test no son opcionales. Un software sin testear es equivalente a dormir encima de una bomba. Acabará explotando. ¡BOOOOMMMM!
Y estos errores, a largo plazo, repercutirán en la salud económica de proyecto.
Aunque ya hablemos respeto a que las pruebas unitarias son la base de la pirámide de las pruebas. Debido a que son baratas y evitan que los errores suban hacía capas superiores. Y con ello, evitamos que el precio de solventar el bug crezca exponencialmente más y más conforme más se eleve el bug en dicha jerarquía.
Acabamos de ver la importancia de hemos visto la importancia de realizar pruebas unitarias.
Las pruebas unitarias, las cajas negras
Los desarrolladores, solemos realizar 2 o 3 casos cuando escribimos un código y si no falla solemos decir que funciona bien. ¿Pero realmente podemos afirmar que ese código está realmente testeado? ¿Creéis que puede subir a producción? La respuesta a ambas preguntas es NO.
Las pruebas unitarias o Unit Testing en inglés, son pruebas donde se testean componentes individuales de un programa (un ejemplo podría ser el testing de una función o de una clase).
Consisten en introducir un conjunto de entradas dentro de un código y determinar si el conjunto de salida es el esperado. Es decir, comprobar si los valores devueltos son correctos o no. Y manejar los fallos, si se proporciona un valor no esperado.
El propósito de este tipo de pruebas, es el garantizar que cada componente funcione aisladamente. También, que todo funciona como se espera que debe funcionar, y que todo responda como debe responder. Y que falla cuando debe y como debe fallar. Y acepta lo que tiene que aceptar.
Las pruebas unitarias generalmente suelen ser la unidad mínima de trabajo del testing. Usualmente, las pruebas unitarias, se realizan sobre un método, una función o una clase. Aunque no siempre es así. En algunas ocasiones, la unidad mínima de trabajo es un conjunto de métodos o de operaciones y no un método o función única. Entendemos como unidad de trabajo, a toda aquella operación o conjunto de operaciones que causa un cambio en el sistema o una respuesta que genera dicho sistema.
Estructura de un Test Unitario
La estructura de un test unitario, está formada por 3 elementos principales:
- Conjunto de entradas.
- Unidad de trabajo a probar.
- Conjunto de salidas.
Secciones de un Test Unitario
Usualmente un test se divide en 3 secciones:
- Etapa de preparación (Arrange): donde se establecen los valores de entrada, así como los valores esperados. Y cualquier otra preparación que se necesite para realizar la prueba unitaria.
- Etapa de acción o de ejecución (Act): donde se ejecuta la prueba sobre la unidad de trabajo a probar.
- Etapa de comprobación (Assert): donde se revisa que las condiciones esperadas se hayan cumplido. Así como que el método haya producido los cambios esperados o haya devuelto el valor esperado.
Características de los test unitarios
Por lo general, el propio programador que escribe el código o la unidad de trabajo, es el que tiene que escribir los test unitarios para probar su código.
En este caso, hay que tener hay que ser precavido, debido a que al ser nosotros los que escribimos el código, puede que nos confiemos en que la unidad de trabajo funciona correctamente. O que escribamos test unitarios menos exigentes, y por tanto, que no contemplen casos que puedan fallar fácilmente, es decir, que no sean muy efectivos.
O que únicamente testees los casos del test que funcionan correctamente o que no escribas los test unitarios en los que tu programa falle (por desconocimiento, apropósito, etc.).. Por todo esto, tienes que ser muy cuidadoso en los casos que estableces para probar tu código.
Ya que a pesar de que puede que existan una infinidad de posibilidad de entradas. Existen casos que son más probables que fallen que otros. Por ejemplo en el caso de que tengamos que introducir un número del 1 al 10 como nota de un examen. Los casos que fallarán con más probabilidad y que, por lo tanto sería recomendable testear mediante a una prueba unitaria los casos como: un campo vacío (null), -100,-10, -1, 0- 1, 5, 10, 11, +100 y luego lo mismo con decimales (ejem: 10.0 y 10,0) y también habría que testear la introducción de caracteres, intentar desbordar el rango máximo del tipo de dato, etc. Con la finalidad de llevar dicho código al límite.
Las pruebas unitarias son independientes del entorno, con esto nos referimos, a que se pueden poder ejecutar en cualquier entorno, nuestro equipo, en el del cliente, en el de producción o en el que sea (siempre que cumplan los requisitos de hardware, etc.).
Cada prueba unitaria es independiente de otras pruebas unitarias. Por tanto, cada unidad de trabajo, depende únicamente de la clase que testea. Los datos se introducen mediante a Mocking, un mecanismo que burla o engaña a la prueba unitaria. Con ello le permitimos introducir datos «hardcodeados» (picados a mano). Por tanto, no dependen de fuentes externas de datos, como ficheros, o información de BBDD.
ada unidad de trabajo, depende únicamente de la clases que testea. Los datos se introducen mediante a Mocking, un mecanismo que burla o engaña a la prueba unitaria. Con ello le permitimos introducir datos «hardcodeados» (picados a mano). Por tanto, no dependen de fuentes externas de datos, como ficheros, o información de BBDD.
Las pruebas unitarias sobre una unidad de trabajo suelen ser rápidas, sobretodo, en sus fases de preparación (arrange) y comprobación (assert). La fase intermedia entre ambas, la ejecución (act), será la que aunque no suele ser lenta tarde lo que tenga que tardar en función de varios factores como por ejemplo, la cantidad de comprobaciones a realizar.
Los unit testing, deben de ser mantenibles, tanto por el propio programador que los desarrolle, como por el resto del equipo de programadores.
Tipos de pruebas unitarias
Las pruebas unitarias, se pueden subdividir en 2 grupos según quién realiza la interacción en:
- Pruebas manuales: las desarrolla el programador, por tanto, podemos afirmar que existe interacción humana.
- Pruebas automatizadas: las desarrolla un software destinado a ello, por tanto, no existe interacción humana.
No hay que elegir entre unas u otras, lo ideal, es la combinación de ambas. Y con ello, aprovechar los beneficios de ambas.
19 agosto, 2021 a las 1:49
Thanks for another informative site. The place else may just I get that kind of info written in such an ideal way?
I’ve a challenge that I am simply now working on, and I’ve been on the glance out for such information.
19 agosto, 2021 a las 2:18
May I simply say what a comfort to discover someone who actually understands
what they’re discussing over the internet. You certainly understand how to bring an issue
to light and make it important. More people should read this and understand this side of your story.
I was surprised that you’re not more popular since you most certainly possess the gift.
19 agosto, 2021 a las 2:57
Just desire to say your article is as astounding.
The clearness to your put up is just nice and that i could suppose you are an expert
in this subject. Fine along with your permission allow me to take hold of your RSS feed to keep updated with coming near near post.
Thanks 1,000,000 and please carry on the enjoyable work.
19 agosto, 2021 a las 4:31
It’s very easy to find out any matter on web as compared to books, as I
found this paragraph at this website.
19 agosto, 2021 a las 5:41
My brother suggested I might like this web site. He was
entirely right. This post truly made my day.
You can not imagine simply how much time I had spent for this info!
Thanks!
19 agosto, 2021 a las 6:59
I have been absent for a while, but now I remember why
I used to love this site. Thanks, I’ll try and check back more frequently.
How frequently you update your site?
Look into my web page :: Viking XL Keto Reviews
19 agosto, 2021 a las 7:29
It’s genuinely very complicated in this full of activity life to listen news on TV, so I only use world wide web for that
reason, and take the hottest news.
Also visit my web page … Pure Keto Burn Pills
19 agosto, 2021 a las 8:04
Oh my goodness! Incredible article dude! Many thanks, However I am having troubles with your RSS.
I don?t understand the reason why I can’t subscribe to it.
Is there anybody getting identical RSS issues? Anyone who knows the solution will
you kindly respond? Thanx!!
Also visit my webpage … http://www.aniene.net
19 agosto, 2021 a las 8:49
I was able to find good advice from your content.
19 agosto, 2021 a las 9:32
I love what you guys are up too. This sort of clever work and exposure!
Keep up the terrific works guys I’ve included you guys to my personal blogroll.
Also visit my page; Green Leaf Hills Review
19 agosto, 2021 a las 9:36
Generally I do not learn article on blogs, however I would like to say that
this write-up very pressured me to check out and do it! Your writing taste
has been amazed me. Thanks, quite great article.
my blog: Libido Boost
19 agosto, 2021 a las 9:38
Great delivery. Outstanding arguments. Keep up the amazing spirit.
My website :: bbs.yunweishidai.com
19 agosto, 2021 a las 10:56
I’ll immediately seize your rss as I can not find your
e-mail subscription link or newsletter service. Do you have
any? Kindly allow me know so that I may subscribe. Thanks.
19 agosto, 2021 a las 12:33
Keep functioning ,terrific job!
Feel free to visit my web blog :: Wawza Apple Cider Gummies Reviews (http://www.diclelife.com/)
19 agosto, 2021 a las 13:13
Thank you a bunch for sharing this with all folks you really know what you’re speaking approximately!
Bookmarked. Kindly also visit my website =). We may have a hyperlink alternate contract between us!
Here is my webpage – Biodermeux Review
19 agosto, 2021 a las 14:28
I seldom comment, however after looking at a few of the responses on this
page Introducción a los Test Unitarios (Unit Testing) – Java desde 0.
I do have a few questions for you if it’s allright. Could it
be only me or does it look like a few of the comments come across
like they are left by brain dead visitors? 😛 And, if you are
posting on additional social sites, I’d like to follow you.
Could you make a list of all of all your social community sites like your
twitter feed, Facebook page or linkedin profile?
Have a look at my web page; Wawza Apple Cider Vinegar
19 agosto, 2021 a las 15:29
Amazing! Its actually awesome piece of writing, I have got much clear idea regarding from this paragraph.
Here is my web site; Libido Boost Male Enhancement Ingredients
19 agosto, 2021 a las 21:18
I am delighted that I observed this weblog, exactly
the right info that I was looking for!
My web blog Green Leaf Hills Reviews
20 agosto, 2021 a las 0:02
I am sure this paragraph has touched all the internet visitors, its really really pleasant piece of writing on building up new weblog.
22 agosto, 2021 a las 12:55
I have to thank you for the efforts you’ve put in writing this site.
I really hope to see the same high-grade blog posts
from you in the future as well. In fact, your creative writing abilities has encouraged me to get my own blog now 😉
Take a look at my web-site … Yoni Pur Reviews
24 agosto, 2021 a las 13:09
Asking questions are truly fastidious thing if you are not understanding something totally, except
this paragraph offers good understanding yet.
28 agosto, 2021 a las 5:26
There’s certainly a lot to know about this topic. I really like
all the points you’ve made.
30 agosto, 2021 a las 4:00
What’s up, I desire to subscribe for this web site to get newest updates,
thus where can i do it please help out.
my web site – Natural Burn Keto Reviews
30 agosto, 2021 a las 4:07
As the admin of this web page is working, no uncertainty very rapidly it will be famous, due to its
feature contents.
4 septiembre, 2021 a las 0:58
My brother recommended I might like this website. He was entirely right.
This post actually made my day. You can not imagine simply
how much time I had spent for this info! Thanks!
5 septiembre, 2021 a las 0:26
Hi there, for all time i used to check webpage posts here in the early hours in the morning, since i love to find out
more and more.
10 septiembre, 2021 a las 0:23
When some one searches for his required thing, thus he/she wishes to be available
that in detail, therefore that thing is maintained
over here. quest bars http://j.mp/3C2tkMR quest bars
11 septiembre, 2021 a las 4:58
Have you ever thought about including a little bit more than just your articles?
I mean, what you say is fundamental and all. Nevertheless think about if you added some great images or videos to give your posts more, «pop»!
Your content is excellent but with images and videos, this
blog could certainly be one of the most beneficial
in its niche. Superb blog! scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery
24 diciembre, 2021 a las 23:57
I pay a visit each day some web sites and sites to read posts, except this web site provides
quality based content.
1 enero, 2022 a las 1:42
Hi! I just wanted to ask if you ever have any
trouble with hackers? My last blog (wordpress) was hacked and
I ended up losing many months of hard work due to no data backup.
Do you have any methods to stop hackers?
8 enero, 2022 a las 2:58
What’s up to all, how is the whole thing, I think every one is getting more from this site, and your views are pleasant designed for new
visitors.
28 noviembre, 2022 a las 16:21
Hi! Do you know if they make any plugins to protect against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?
Also visit my web-site; tracfone special coupon 2022
30 noviembre, 2022 a las 16:39
Hmm it looks like your blog ate my first comment (it was extremely long) so
I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog.
I too am an aspiring blog blogger but I’m still new to everything.
Do you have any tips for rookie blog writers? I’d really appreciate it.
my blog post – tracfone 2022
6 junio, 2023 a las 10:16
Thank you for your shening. I am worried that I lack creative ideas. It is your enticle that makes me full of hope. Thank you. But, I have a question, can you help me? https://accounts.binance.com/en/register-person?ref=P9L9FQKY
9 junio, 2023 a las 5:53
This article opened my eyes, I can feel your mood, your thoughts, it seems very wonderful. I hope to see more articles like this. thanks for sharing.
6 agosto, 2023 a las 20:04
Superb knowledge. Cheers!
cheap essay writing service us legit essay writing service legitimate essay writing service
21 marzo, 2024 a las 10:24
Undeniably bеlieve thɑt which yⲟu saіd.
Yourr favorite justification appeared tо ƅe at tthe
web the simplest thing to take note of. I sayy to yоu, I
definitelpy get annoyed whijle peopole consiuder issues tһat tһey just don’t recognize aƄoᥙt.
Уou controlled tօ hhit thе nail upon the top ɑnd
also defined out tһe whole thing ᴡithout having side-effects ,
other folk c᧐uld take а signal. Willl proobably Ƅe agaіn to gett more.
Thank you