简体   繁体   English

Junit | 如何在方法中测试参数

[英]Junit | How to test parameters in a method

How do I test parameters inside a method itself. 如何在方法本身内部测试参数。 For example 例如

class TestClass {

public void paraMethod(String para1, String para2) {
         String testPara1 = para1;
         String testPara2 = para2; 
}
}

class TestingClass {

   @Test
   public void testParaMethod () throws Exception {
             String myPara1 = "MyPara1"; 
             String myPara2 = "MyPara2";

             new TestClass().paraMethod(myPara1, myPara2);

   }
}

Ok, so is it possible to test if the testPara1 and testPara2 are properly set to the values that I have passed? 好的,是否可以测试testPara1testPara2是否正确设置为我已通过的值?

Thanks. 谢谢。

It is neither possible nor desirable to test the values and state changes of local variables of a method. 测试方法的局部变量的值和状态变化既不可能也不希望。 They are private details of the implementation, not something you are expected to test. 它们是实现的私有细节,不是您应该测试的细节。

Instead, your tests should judge the correctness of a method by observing something visible from the outside, such as return values, interactions with mocked environment, or externally visible changes of the object's state. 相反,您的测试应该通过观​​察外部可见的事物来判断方法的正确性,例如返回值,与模拟环境的交互或对象状态的外部可见变化。

If I understand you correctly, you want to test that the variables testPara1 and testPara2 hold the values supplied to para1 and para2 respectively. 如果我对您的理解正确,则需要测试变量testPara1和testPara2是否分别具有提供给para1和para2的值。 Given that the method does nothing, it shouldn't really matter. 鉴于该方法无济于事,因此它实际上并不重要。

To improve your unit test pick a name that describes what the method does. 为了改善单元测试,请选择一个描述方法用途的名称。 Decide what the out come is (a value is returned, some state is changed) and test for the expected outcome based on known input. 确定结果(返回值,更改某些状态),然后根据已知输入测试预期结果。 Write your test without implementing the method, thinking about valid/invalid input and possible edge cases. 在不执行该方法的情况下编写测试,请考虑有效/无效的输入以及可能的边缘情况。 Then implement you method until all tests pass - when they do move on. 然后实施您的方法,直到所有测试通过为止。

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

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