简体   繁体   English

Junit-如何测试参数的无效用法

[英]Junit- how to test invalid usage of parameters

I am supposed to write a Junit test for the invalid usage of correct parameters. 我应该为正确参数的无效用法编写一个Junit测试。 I am a bit confused by this concept. 这个概念让我有些困惑。 Can someone please help to explain what is this scenario, and how to do this with an example? 有人可以帮忙解释一下这种情况,以及如何通过一个例子来做到这一点吗?

I am testing a method that take a customer and a type of service as parameters. 我正在测试一种以客户和服务类型为参数的方法。 and I've tried the assertFalse method below, and tried to pass two customers to 并且我尝试了下面的assertFalse方法,并试图将两个客户传递给

assertFalse("Registration fails for add two services to one customer", cs.addPeople("Jack", "Jill","Cleaning"));

I realized that this is not the correct way as the add.People() method only takes one person as a parameter. 我意识到这不是正确的方法,因为add.People()方法仅将一个人作为参数。 In this case how can we test invalid usage? 在这种情况下,我们如何测试无效用法? Many thanks! 非常感谢!

By test invalid usage of parameters, I guess you mean write scenarios with invalid parameters. 通过测试参数的无效用法,我猜您的意思是使用无效参数编写方案。 For example. 例如。 Say that you have a method: 假设您有一个方法:

public Integer toInteger(String input){
   //conversion logic
}

Now, you would want to know how your method behaves on different scenarios. 现在,您将想知道您的方法在不同情况下的行为。 One scenario would be passing invalid parameter such as null , and see how your method behaves. 一种情况是传递无效参数(例如null ,并查看您的方法的行为。

@Test
public void testToIntegerForNullParam(){
   myClass.toInteger(null);
}

This method will not pass if you didn't handle null checking, and you will have to refactor to pass this test. 如果您不处理null检查,则此方法将不会通过,您将必须重构以通过此测试。

public Integer toInteger(String input){
   if(input == null){
      throw new IllegalArgumentException("Argument was null!"); 
    }
    //conversion logic
}

Then in your test, you can test if this indeed throws exception when argument is null. 然后在测试中,您可以测试当参数为null时,是否确实引发异常。 You can use expected = IllegalArgumentException.class 您可以使用expected = IllegalArgumentException.class

@Test(expected = IllegalArgumentException.class)
public void testToIntegerForNullParam(){
    myClass.toInteger(null);
}

You can continue adding more scenarios such as string not being numeric etc. 您可以继续添加更多方案,例如字符串不是数字等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM