@Autowired public PlugsModel(Environment env){ // public PlugsModel(Environment env) throws Exception { this.broker=env.getProperty("mqtt.broker"); this.clientId=env.getProperty("mqtt.client"); this.topicPrefix=(String)env.getProperty("mqtt.topicPrefix"); }用@beforeclass写测试用例
时间: 2023-05-31 15:06:35 浏览: 55
由于`@BeforeClass`注解只能用于静态方法,而构造函数是非静态方法,因此无法使用`@BeforeClass`注解来写测试用例。
您可以使用JUnit的`@RunWith`注解和`@Before`注解来编写测试用例。具体实现如下:
```
@RunWith(SpringRunner.class)
public class PlugsModelTest {
private static Environment env;
private PlugsModel plugsModel;
@Before
public void setUp() {
env = new MockEnvironment()
.withProperty("mqtt.broker", "tcp://localhost:1883")
.withProperty("mqtt.client", "test-client")
.withProperty("mqtt.topicPrefix", "test-topic");
plugsModel = new PlugsModel(env);
}
@Test
public void testBroker() {
String broker = plugsModel.getBroker();
Assert.assertEquals("tcp://localhost:1883", broker);
}
@Test
public void testClientId() {
String clientId = plugsModel.getClientId();
Assert.assertEquals("test-client", clientId);
}
@Test
public void testTopicPrefix() {
String topicPrefix = plugsModel.getTopicPrefix();
Assert.assertEquals("test-topic", topicPrefix);
}
}
```
在`setUp()`方法中,我们使用`MockEnvironment`来模拟`Environment`接口,并设置所需的属性值。然后,我们创建一个`PlugsModel`对象,并在每个测试方法中验证对象的属性值是否正确。
请注意,由于我们使用了`@RunWith(SpringRunner.class)`注解,因此可以使用Spring的依赖注入功能,这样我们就可以将`Environment`对象注入到测试类中。