JMockit: @Mocke and MockUp combination in the same test

二次信任 提交于 2020-01-16 02:55:08

问题


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;
            }
        };
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/18769669/jmockit-mocke-and-mockup-combination-in-the-same-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!