简体   繁体   中英

Play Framework 2.1.1 doesn't invoke mockito.

I'm trying to mock Model.finder to test my service, but it seems mockito isn't being injected for some reason and I cannot figure out why. Please help.

public static Result deals() {
    List<Product> finder = new Model.Finder<Long, Product>(Long.class, Product.class).all();
    JsonNode jsonNode = Json.toJson(finder);

    return ok(Json.stringify(jsonNode));
}

And here's my test

@Mock
    private Model.Finder finder;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
        start(fakeApplication());

        Product product = new Product();
        product.id = 1L;
        product.title = "Milk";

        List<Product> products = Arrays.asList(product);

        when(finder.all()).thenReturn(products);

    }

    @Test
    public void shouldGetDeals() {
        Result result = routeAndCall(fakeRequest(GET, "/products"));
        assertThat(status(result), is(200));

        String deals = contentAsString(result);

        assertThat(deals, containsString("Milk"));
    }

So, the result is that Model.Finder returns 0 because the mock is not invoked. I'm not sure if this is how you mock in Play 2.1?

Your deals() method is making a new Finder , rather than using the mock one that you created. You're going to need to refactor your code a little, to make it more testable. You may want to read https://code.google.com/p/mockito/wiki/MockingObjectCreation for a couple of ideas on how you could do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM