0
我正在为我的REST-API编写单元测试,并且在创建实体模拟时遇到了一些问题。我不知道我该如何模拟EntityManager。我尝试了下面的例子,但是我得到了一个错误。模拟:when()需要参数必须是'模拟方法调用'
我ControllerTest:
public class MControllerTest {
private MockMvc mockMvc;
@InjectMocks A a;
@InjectMocks B b;
@InjectMocks AController aController;
@InjectMocks private AServiceImpl aServiceImpl;
@Autowired WebApplicationContext webApplicationContext;
@Autowired private FilterChainProxy springSecurityFilterChain;
@Autowired
@InjectMocks
private EntityManagerFactory entityManagerFactory;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(springSecurityFilterChain)
.build();
}
@Test
public void postATest() throws Exception {
a.setDDDD("XXX");
EntityManagerFactory entityManagerFactory = webApplicationContext.getBean(EntityManagerFactory.class);
EntityManager entityManager = entityManagerFactory.createEntityManager();
when(this.entityManagerFactory.createEntityManager()).thenReturn(entityManager);
when(aServiceImpl.createEntity(isA(A.class))).thenReturn(a);
b.setCCCC;
a.setMovieTranslations(Arrays.asList(b));
when(aServiceImpl.createEntity(isA(B.class))).thenReturn(a);
mockMvc.perform(post("/path")
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
}
的createEntityMethod:
public Object createEntity(T t) {
try {
entityManager.persist(t);
return t;
} catch (IllegalArgumentException | EntityExistsException | ...
}
错误日志:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.x.server.controller.MControllerTest.postATest(MControllerTest.java:121)
当我不上了EntityManager注入模拟对象,我得到了带有此错误日志的坚持方法的空指针异常:
java.lang.NullPointerException: null
at com.x.server.serviceImpl.AManageServiceImpl.createEntity(AManageServiceImpl.java:45)
at com.eza.server.controller.MControllerTest.postATest(MControllerTest.java:123)
有人可以帮我吗?
我不知道为什么你混的春天一样的Mockito那。要么你需要这些“真正的”豆,那么你正在创建一个整合测试,你很可能不需要mockito。或者你正在创建一个单元测试,每个依赖bean被嘲笑。 – Tom
你是对的。谢谢。你评论解决我的问题。它正在工作。我现在只使用mockito。 – emoleumassi
很高兴听到。请写下你现在工作的代码和你已经改变的答案,以便将来的读者可以从中学习:)。 – Tom