dimanche 7 février 2016

Mock: when() requires an argument which has to be 'a method call on a mock'

i am writing the unit tests for my REST-API and have some problems with the entities creation mocking. i don't know how can i mock the EntityManager. I tried the example below but i got an error.

My ControllerTest:

public class MControllerTest {

    @InjectMocks
    A a;
    @InjectMocks
    B b;
    private MockMvc mockMvc;
    @InjectMocks
    AController aController;
    @Autowired
    WebApplicationContext webApplicationContext;
    @Autowired
    private FilterChainProxy springSecurityFilterChain;
    @Autowired
    @InjectMocks
    private EntityManagerFactory entityManagerFactory;
    @InjectMocks
    private AServiceImpl aServiceImpl;

    @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();
    }

The createEntityMethod:

public Object createEntity(T t) {
    try {
        entityManager.persist(t);
        return t;
    } catch (IllegalArgumentException | EntityExistsException | ...
}

the error log:

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)

when i don't inject a mock object on the EntityManager, i got a nullpointer exception by the persist method with this error log:

java.lang.NullPointerException: null
    at com.x.server.serviceImpl.AManageServiceImpl.createEntity(AManageServiceImpl.java:45)
    at com.eza.server.controller.MControllerTest.postATest(MControllerTest.java:123)

can someone help me?

Cheers

Aucun commentaire:

Enregistrer un commentaire