@Autowired public PlugsModel(Environment env) throws Exception { // 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"); } synchronized protected void handleUpdate(String topic, MqttMessage msg){ logger.info(">>> handleUpdate: {} {}", topic, msg); String[] nameUpdate=topic.substring(topicPrefix.length()+1).split("/"); if ((nameUpdate.length!=3)||!nameUpdate[0].equals("update")){ return; //ignore unknown format }; logger.info(">>> handleUpdate {} {}", nameUpdate[1], nameUpdate[2]); switch(nameUpdate[2]){ case "state": states.put(nameUpdate[1], msg.toString()); break; case "power": powers.put(nameUpdate[1], msg.toString()); default: return; } }不用mock environment怎么写testcase
时间: 2023-06-02 22:01:58 浏览: 59
如果不使用mock environment,则需要在测试类中手动设置环境变量,以便在测试中使用。可以使用@Before注释来设置环境变量,例如:
```
@Before
public void setUp() {
System.setProperty("mqtt.broker", "tcp://localhost:1883");
System.setProperty("mqtt.client", "testClient");
System.setProperty("mqtt.topicPrefix", "testPrefix/");
}
```
然后,可以创建PlugsModel实例并调用其方法进行测试,例如:
```
@Test
public void testHandleUpdate() {
PlugsModel model = new PlugsModel(System.getenv());
MqttMessage msg = new MqttMessage("on".getBytes());
model.handleUpdate("testPrefix/update/plug1/state", msg);
assertEquals("on", model.states.get("plug1"));
}
```
注意,这里使用System.getenv()来获取环境变量。如果使用System.getProperty()来获取环境变量,则需要用-D参数在运行时设置。例如:
```
java -Dmqtt.broker=tcp://localhost:1883 -Dmqtt.client=testClient -Dmqtt.topicPrefix=testPrefix/ MyTest
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)