@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"); }不用mock environment怎么写testcase
时间: 2023-05-31 11:04:50 浏览: 181
如果不使用mock environment,可以尝试使用一个自定义的TestConfiguration来提供测试所需的属性值。例如:
```java
@RunWith(SpringRunner.class)
public class PlugsModelTest {
@TestConfiguration
static class TestConfig {
@Bean
public PlugsModel plugsModel() {
Environment environment = new StandardEnvironment();
((StandardEnvironment) environment).getPropertySources().addFirst(new MapPropertySource("test", Collections.singletonMap("mqtt.broker", "test.broker")));
return new PlugsModel(environment);
}
}
@Autowired
private PlugsModel plugsModel;
@Test
public void testConstructor() {
assertEquals("test.broker", plugsModel.getBroker());
// other assertions
}
}
```
这里我们创建了一个TestConfiguration来提供测试所需的属性值,并通过添加一个MapPropertySource来模拟环境属性。在PlugsModelTest中,我们使用@Autowired来注入从TestConfiguration中创建的PlugsModel实例,并执行测试。
阅读全文