【发布时间】:2019-08-27 05:23:32
【问题描述】:
我有一个自动装配的变量
@Autowired
private DocumentConfig documentConfig;
我想用这个配置对象的各种状态来测试 DocumentService。我有哪些选择?最好的选择是什么?
第一个想法是这样的:
@Test
public void save_failure() {
documentConfig.setNameRequired(true);
/*
testing code goes here
*/
documentConfig.setNameRequired(false);
}
但我想更加确定变量在测试后被重置以不干扰其他测试,以确保只有这个测试会出错,如果它是问题的根源。
我的新想法是这样的:
@Before
public void after() { documentConfig.setNameRequired(true); }
@Test
public void save_failure() {
/*
testing code goes here
*/
}
@After
public void after() { documentConfig.setNameRequired(false); }
但是,这根本不起作用,因为之前和之后执行的是整个文件,而不是这个单一的测试。我不希望只为一个测试创建一个新文件。
我现在已经达成妥协:
@Test
public void save_failure() {
documentConfig.setNameRequired(true);
/*
testing code goes here
*/
}
@After
public void after() { documentConfig.setNameRequired(false); }
它似乎可以满足我的所有需求,但我有几个问题。
假设nameRequired 开始为假,这是否保证不会干扰其他测试?
有什么办法可以让我更清楚吗?既是为了我未来的自己,也是为了他人。
【问题讨论】:
-
你在测试什么? DocumentConfig,还是其他依赖 DocumentConfig 的类?如果是前者,请使用 try/finally。如果是后者,模拟 DocumentConfig。
标签: java unit-testing spring-boot junit