我想测试以下测试代码,以便在测试代码中创建对象时是否使用给定的配置参数。为了实现这一点,我尝试在开始时覆盖config参数,捕获对象并断言是否正确设置了字段。
不幸的是,application.conf中的配置参数不会被我的测试值覆盖。怎么了?如何覆盖测试的config参数?
application.conf:
email.default_from_address="my@company.com"
email.default_from_name="MyCompany"
测试:
@Test
public void testReadFromConfig() throws IOException, MandrillApiError {
final Map<String, String> testConfig = new HashMap<>();
final String fromName = "UnitTest From";
final String fromEmail = "from@unittest.com";
testConfig.put("email.default_from_name", fromName);
testConfig.put("email.default_from_address", fromEmail);
testConfig.putAll(inMemoryDatabase());
running(fakeApplication(testConfig), () -> {
MandrillEmailService emailService = new MandrillEmailService(
mockedMandrillApi);
EmailMessage testMessage = createTestMessageHelper(
EmailMessage.CONTENT_TYPE.TEXT_HTML);
emailService.send(testMessage);
});
ArgumentCaptor<MandrillMessage> captorForMandrillMsg =
ArgumentCaptor.forClass(MandrillMessage.class);
verify(mockedMessagesApi).send(captorForMandrillMsg.capture(), eq(false));
MandrillMessage capturedMandrillMsg = captorForMandrillMsg.getValue();
assertEquals(fromName, capturedMandrillMsg.getFromName());
assertEquals(fromEmail, capturedMandrillMsg.getFromEmail());
}
错误:
failed: expected:<[UnitTest From]> but was:<[MyCompany]>
答案 0 :(得分:0)
我发现在Play
测试框架中覆盖配置非常困难。它必须是Play
错误。如果您不熟悉GlobalSettings
课程,则此处为resource。尝试覆盖onLoadConfig
方法之一,如下所示:
@Override
public Configuration onLoadConfig(Configuration config, File path, ClassLoader classloader) {
if(Play.isTest()){
// load test configuration and overwrite properties programmatically.
}
}
答案 1 :(得分:0)
我的失败。上面提到的代码有效。问题是我在静态块中读取了配置......
public class MandrillEmailService implements EmailService {
private final static String FROM_ADDRESS;
private final static String FROM_NAME;
private final MandrillApi mandrillApi;
static {
FROM_ADDRESS = Play.application().configuration()
.getString("email.default_from_address");
FROM_NAME = Play.application().configuration()
.getString("email.default_from_name");
}
...