【发布时间】:2018-08-31 07:01:51
【问题描述】:
我在将模拟注入到我需要测试的一个类中时遇到问题。我正在尝试模拟一个 Dao 类,并且在我正在使用的各种服务中使用 ReflectionTestUtils 这样做没有问题,但是这个只是不想工作,它不断调用 Dao 类并从数据库中获取错误。
这是测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class DedicationControllerTest extends AbstractRestTest {
@Mock
UserDaoImpl userDao;
@Autowired
@InjectMocks
GrantedAuthoritiesLevelsHolder grantedAuthoritiesLevelsHolder;
@Test
public void shouldTest() throws Exception {
//given
String json = this.getJsonFromFile("json/my.json");
Mockito.when(userDao.getUser(Mockito.anyString())).thenReturn(new User(1l, "mock"));
ReflectionTestUtils.setField(grantedAuthoritiesLevelsHolder, "userDao", userDao);
ResultActions result = mockMvc.perform(post( controllerUrl + "/action")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json));
// then
result
.andExpect(status().isOk());
}
}
这是我试图注入模拟的类:
@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GrantedAuthoritiesLevelsHolder {
@Autowired
private UserDao userDao;
// some methods
}
【问题讨论】:
-
你为什么在 GrantedAuthoritiesLevelsHolder 对象上使用@Autowired
-
为了在 Spring 测试中模拟事物,我使用 Spring 中的 @MockBean 注解。你试过了吗?
标签: java spring mockito junit4