lundi 28 septembre 2015

Mock object method call using Spring Boot and Mockito

am trying to write Test for this class (Java Spring Boot): http://ift.tt/1O4vGza

Specifically, I am trying to Mock this method call:

URI uri = util.getServiceUrl("product");

I figured I should Mock the ServiceUtils object in order to do this. I tried this using the @Mock and @InjectMocks annotations:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ProductCompositeServiceApplication.class)
public class ProductCompositeIntegrationTest {

    @InjectMocks
    @Autowired
    private ProductCompositeIntegration productIntegration;

    @Autowired
    private RestTemplate restTemplate;

    @Mock
    private ServiceUtils util;

    private MockRestServiceServer mockServer;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void myTest() {
        Mockito.when(util.getServiceUrl("product")).thenReturn(URI.create("http://localhost:8080/test"));
        ResponseEntity<Iterable<Product>> products = productIntegration.getAllProducts();
    }
}

But this way it still calls the original ServiceUtils object, and not the Mocked one. (Also tried without the @Autowired annotation at the ProductCompositeIntegration, but this results in a NullPointerException)

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire