Pregunta

What I have to do:

I have to test my spring mvc with JMockit. I need to do two things:

  1. Redefine MyService.doService method
  2. Check how many times redefined MyService.doService method is called

What the problem:

To cope with the first item, I should use MockUp; to cope with the second item I should use @Mocked MyService. As I understand this two approaches are overriding each other.

My questions:

  1. How to override MyService.doService method and simultaneously check how many times it was invoked?
  2. Is it possible to avoid mixing a behaviour & state based testing approaches in my case?

My code:

@WebAppConfiguration
@ContextConfiguration(locations = "classpath:ctx/persistenceContextTest.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class MyControllerTest extends AbstractContextControllerTests {

    private MockMvc mockMvc;

    @Autowired
    protected WebApplicationContext wac;

    @Mocked()
    private MyServiceImpl myServiceMock;

    @BeforeClass
    public static void beforeClass() {

       new MockUp<MyServiceImpl>() {
            @SuppressWarnings("unused")
            @Mock
            public List<Object> doService() {
                return null;
            }
        };
    }

    @Before
    public void setUp() throws Exception {
        this.mockMvc = webAppContextSetup(this.wac).build();
    }

    @Test
    public void sendRedirect() throws Exception {
        mockMvc.perform(get("/doService.html"))
                .andExpect(model().attribute("positions", null));

        new Verifications() {
            {
                myServiceMock.doService();
                times = 1;
            }
        };
    }
}
¿Fue útil?

Solución

I don't know what gave you the impression that you "should use" MockUp for something, while using @Mocked for something else in the same test.

In fact, you can use either one of these two APIs, since they are both very capable. Normally, though, only one or the other is used in a given test (or test class), not both.

To verify how many invocations occurred to a given mocked method, you can use the "invocations/minInvocations/maxInvocations" attributes of the @Mock annotation when using a MockUp; or the "times/minTimes/maxTimes" fields when using @Mocked. Choose whichever one best satisfies your needs and testing style. For example tests, check out the JMockit documentation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top