您如何测试是否使用junit语句? [英] how do you test if statements with junit?

查看:91
本文介绍了您如何测试是否使用junit语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎在网上找不到任何可解决此问题的教程

我有这个if声明:

if (basket.getCustomerId() != null) {
                Basket exBasket = findBasketByCustomerId(basket.getCustomerId());
                if (exBasket != null && exBasket.getBasketId() != null) {
                    return exBasket;
                }

我想编写一个单元测试,将测试每一行以查看它是否做对了.

有什么想法吗?

@Test
    public void testBasketWithANullCustomerId(){
        basketInformationServiceImpl.createBasket(mockBasket);
        assertNotNull(mockBasket.getCustomerId());
    }

解决方案

单元测试的目的不是测试声明,而是测试方法.正确的做法不是考虑这条线,而是考虑它出现的方法,并询问您要该方法做什么:它需要什么样的输入,以及应该产生什么样的输出? /p>

然后编写接受一些典型输入的测试,并检查它们是否提供正确的输出以及一些 edge case 输入(例如null,0,等),并检查您是否也获得了正确的输出.

如果这是您的整个方法(实际上不是,但是,如果这是它的本质),我将进行测试:

  • 具有null客户ID的basket
  • 一个null篮子(除非您确定这永远不会发生),因为当前这段代码将给出一个NullPointerException;
  • 带有客户ID的购物篮,应该可以让您找到已知的exBasket;
  • 具有客户ID的购物篮,该ID将返回nullexBasket;
  • 具有客户ID的购物篮,该客户ID将返回不为null的exBasket,但其购物篮ID为null.

I can't seem to find any tutorials online that address this

I have this if statement:

if (basket.getCustomerId() != null) {
                Basket exBasket = findBasketByCustomerId(basket.getCustomerId());
                if (exBasket != null && exBasket.getBasketId() != null) {
                    return exBasket;
                }

and I want to write a unit test that will test each individual line to see if it is doing the right thing.

Any ideas?

@Test
    public void testBasketWithANullCustomerId(){
        basketInformationServiceImpl.createBasket(mockBasket);
        assertNotNull(mockBasket.getCustomerId());
    }

解决方案

The purpose of unit testing isn't to test statements but methods. The right thing to do is not to consider this line, but to consider the method that it appears in, and ask what you want that method to do: what sort of input does it take, and what sort of output should it produce?

Then write tests that take some typical inputs, and check that they give correct outputs, and also some edge case inputs (like null, 0, Integer.MAX_VALUE, etc.) and check that you get the right outputs for those too.

If this is your entire method (which actually it can't be, but if it's the essence of it), I'd test:

  • a basket with a null customer ID;
  • a null basket (unless you're certain this can never happen), because currently this code will give a NullPointerException;
  • a basket that has a customer ID that should allow you to find a known exBasket;
  • a basket that has a customer ID that will return an exBasket of null;
  • a basket that has a customer ID that will return an exBasket that isn't null, but whose basket ID is null.

这篇关于您如何测试是否使用junit语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆