我目前无法尝试为这段代码创建一个单元测试。老实说,我根本无法弄清楚如何为这些代码行创建单元测试。我在网上查了多个地方,找不到任何东西。可能只是因为我不了解单元测试,所以我无法弄清楚如何创建这个,但有人可以帮我吗?
public List<Overview> findOverviewByStatus(String status) throws CustomMongoException {
List<Overview> scenarioList = new ArrayList<Overview>();
LOGGER.info("Getting Scenario Summary Data for - {}", status);
Query query = new Query(Criteria.where("status").is(status));
if (mongoTemplate == null)
throw new CustomMongoException("Connection issue - Try again in a few minutes",
HttpStatus.FAILED_DEPENDENCY);
LOGGER.info("Running Query - {}", query);
scenarioList = mongoTemplate.find(query.with(new Sort(Sort.Direction.DESC, "lastUpdatedDate")), Overview.class);
return scenarioList;
}
答案 0 :(得分:0)
所以你想对方法进行单元测试。首先假装你不知道代码是什么样的(黑盒测试)。
What happens if you call it with status of null, and then status of empty string?
What are some status string that return expected values?
将所有这些作为断言添加到测试方法中,以确保如果有人在将来更改此方法,则单元测试会确保它返回预期结果。
这就是单元测试通常所做的全部工作,确保代码以可预测的方式运行,并防止违反您在编写时为方法创建的合同的更改。
例如:
import org.junit.Assert;
import org.junit.Test;
public class MyObjectTest {
@Test
public void testMyObjectMethod() {
// Create the object that contains your method (not in the sample you provided)
MyObjectToTest obj = new MyObjectToTest();
// Check that for a null status you get some result (assuming you want this)
Assert.assertNotNull(obj.findOverviewByStatus(null));
// Lets assume that a null status returns an empty array, add a check for it
Assert.assertTrue("null parameter size should be 0", obj.findOverviewByStatus(null).size() == 0);
//etc...
}
}