Spring boot bean构造函数中的对象为空
我在Spring boot bean构造函数中的对象为空,spring-boot,spring-boot-test,Spring Boot,Spring Boot Test,我在应用程序.yml中记录了异常消息。它们是纯文本,稍后使用java.text.MessageFormat重新格式化 当登录失败时,我得到了以下自定义RuntimeException我的服务抛出: @Component public class AccountLoginFailedException extends RuntimeException { @Autowired public AccountLoginFailedException(@Value("#(${authse
应用程序.yml
中记录了异常消息。它们是纯文本,稍后使用java.text.MessageFormat
重新格式化
当登录失败时,我得到了以下自定义RuntimeException
我的服务抛出:
@Component
public class AccountLoginFailedException extends RuntimeException {
@Autowired
public AccountLoginFailedException(@Value("#(${authservice.exception-messages.login-failed})") final String message, @Qualifier(value = "Credentials") final Credentials credentials) {
super(MessageFormat.format(message, credentials.getUsername()));
}
}
我的测试,它只测试AccountController
,并模仿它背后的服务:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AuthServiceTestConfiguration.class)
@WebMvcTest(AccountController.class)
public class AccountControllerTest {
@Autowired
private BeanFactory beanFactory;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private TestHelper helper;
@MockBean
private AccountService accountService;
@Autowired
private JwtService jwtService;
@Autowired
private MockMvc mvc;
@Test
public void test_LoginFailed_AccountDoesNotExist() throws Exception {
// Given
final Credentials credentials = helper.testCredentials();
final String credentialsJson = objectMapper.writeValueAsString(credentials);
final AccountLoginFailedException loginFailedException = beanFactory.getBean(AccountLoginFailedException.class, credentials);
// When
given(accountService.login(credentials)).willThrow(loginFailedException);
// Then
mvc
.perform(
post("/login")
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(credentialsJson))
.andExpect(status().isUnprocessableEntity())
.andExpect(jsonPath("$.data").value(equalTo(loginFailedException.getMessage())));
}
}
消息
包含正确的字符串
但是:凭据
只包含一个空对象(不是null),而不是使用helper.testCredentials()
创建的对象
下面是我使用的一个稍微简化的TestHelper
类:
@TestComponent
public class TestHelper {
public static final String USERNAME = "SomeUsername";
public static final String PASSWORD = "SomePassword";
@Autowired
private BeanFactory beanFactory;
public Credentials testCredentials() {
final Credentials credentials = beanFactory.getBean(Credentials.class.getSimpleName(), Credentials.class);
credentials.setUsername(USERNAME);
credentials.setPassword(PASSWORD);
return credentials;
}
}
这些自定义异常仅由我的应用程序引发,并且始终应包含负责该异常的凭据(用户名)。我还有一个AccountExceptionsControllerAdvice
-类,它将这些自定义异常封装在一个通用JSON响应中,以一种首选的方式公开错误
如何确保将
凭证的此特定实例插入到AccountLoginFailedException的特定实例中?或者我根本不应该是自动连线异常吗?
您可以在测试中模拟您的凭证
组件,如下所示:
@MockBean
private Credentials credentials;
@Before
public void before() {
when(credentials.getUsername()).thenReturn(USERNAME);
when(credentials.getPassword()).thenReturn(PASSWORD);
}
模仿托斯是不对的。真的没有别的办法吗?