写一段junit,如果参数为null则进行初始化,如果不为空则输出参数内容
时间: 2024-01-21 14:16:23 浏览: 22
假设我们要测试的类名为TestDemo,可以写出如下的JUnit测试方法:
```java
import org.junit.Test;
import static org.junit.Assert.*;
public class TestDemoTest {
@Test
public void testPrintIfNotNull() {
TestDemo testDemo = new TestDemo();
String input = "Hello, World!";
String expectedOutput = "Hello, World!";
String actualOutput = testDemo.printIfNotNull(input);
assertEquals(expectedOutput, actualOutput);
}
@Test
public void testPrintIfNull() {
TestDemo testDemo = new TestDemo();
String input = null;
String expectedOutput = "Initialized";
String actualOutput = testDemo.printIfNotNull(input);
assertEquals(expectedOutput, actualOutput);
}
}
```
在上面的代码中,我们定义了一个TestDemo类,其中有一个printIfNotNull方法,该方法接收一个字符串参数,如果该参数不为空,则输出该参数内容,否则输出"Initialized"。
我们编写了两个测试方法:testPrintIfNotNull和testPrintIfNull。在testPrintIfNotNull方法中,我们传入一个非空字符串作为参数,期望输出和输入字符串相同。在testPrintIfNull方法中,我们传入一个空字符串作为参数,期望输出"Initialized"。我们可以用assertEquals方法来比较期望输出和实际输出是否相同。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)