Mokito在运行JUnit测试时没有使用Jersey和Jetty

时间:2016-04-26 21:30:47

标签: java junit jersey jetty mockito

在测试Jersey REST OrderResource时,它返回空List<Order> orders。 Mockito部分似乎工作不正确,因为它访问数据库层。怎么解决?

测试

 public class OrderResourceTest extends JerseyTest {
    @Mock
    private OrderService orderServiceMock;

    @Override
    protected Application configure() {
        MockitoAnnotations.initMocks(this);
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);
        //database set up
        ResourceConfig resourceConfig = new ResourceConfig(OrderResource.class);

        return resourceConfig;
    }

    @Test
    public void testGetOrders() {
        when(orderServiceMock.findOrders()).thenReturn(getMockOrders());

        Response response = target("/orders")
            .request()
            .get();
        List < Order > orders = response.readEntity(new GenericType < List < Order >> () {});
        assertEquals("Should return status 200", 200, response.getStatus());
        assertTrue(orders.size() == 1); // orders.size() is 0. Why?
    }


    private List < Order > getMockOrders() {
        Customer customer = new Customer(1 L, "CompanyName", "Street", "123456", "City", "UK");
        List < OrderLine > orderLines = Arrays.asList(new OrderLine(1 L, "s345664lkdLDSDf", "Samsung Galaxy 4", 1));
        Order order = new Order(1 L, customer, orderLines);

        return Arrays.asList(order);
    }
}

project用作参考

1 个答案:

答案 0 :(得分:0)

示例中缺少的关键部分是InjectableProvider

class InjectableProvider extends AbstractBinder implements Factory<CustomerService> {
    @Override
    protected void configure() {
        bindFactory(this).to(CustomerService.class).in(Singleton.class);
    }

    public CustomerService provide() {
        return serviceMock;
    }

    public void dispose(CustomerService service) {
        serviceMock = null;
    }
}

将模拟注入资源是提供者的工作。如果您按照相同的方法并为OrderService自定义它,则应调用您的模拟。

确保在配置期间注册:

config.register(new InjectableProvider());