利用powermock+testng编写测试public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; }
时间: 2024-06-11 18:04:23 浏览: 135
首先,需要在项目的pom.xml文件中添加PowerMock和TestNG的依赖:
```xml
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>
```
然后,编写测试类:
```java
import org.powermock.api.mockito.PowerMockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class TopicTest {
private Topic topic;
@BeforeMethod
public void setUp() {
topic = PowerMockito.spy(new Topic());
}
@Test
public void testGetTopic() {
String expected = "Test topic";
topic.setTopic(expected);
String actual = topic.getTopic();
assertEquals(actual, expected);
}
}
```
在这个测试中,我们使用PowerMockito.spy()方法创建Topic类的一个Spy对象,这样我们就可以对其进行模拟。然后,我们设置topic属性并使用getTopic()方法获取它,并使用TestNG的Assert.assertEquals()方法来比较期望的和实际的值。
最后,我们可以在测试运行器中执行这个测试类,例如使用Maven Surefire插件:
```xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
```
这样,我们就可以运行mvn test命令来执行测试。
阅读全文