jeudi 4 février 2016

Jmockit how to mock static method for each single test

I know there is @Injectable annotation but can't figure out if it suits my case:

A class contains a static method call:

public class ClassToTest(){
public void evilMethod(){
//do something
Blob blob = Hibernate.getLobCreator(session).createBlob(new byte[]{0});
// do something
}
}

I mock it like this:

public Blob createEmptyBlob() throws Exception {
        final Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(new byte[0]);
        new MockUp<Hibernate>() {
            @Mock
            public LobCreator getLobCreator(Session session) {
                return new MockUp<LobCreator>() {
                    @Mock
                    public Blob createBlob(byte[] bytes) throws SQLException {
                        return blob;
                    }
                }.getMockInstance();
            }
        };
        return blob;
    }

And there is another test class with several test methods for ClassToTest where I call createEmptyBlob() in each method.

Problem is: when I call createEmptyBlob() more then once it returns the same mocked blob instead of creating and mocking a new one.

Is it possible to somehow mock one static call only. So that in each test a new mock blob is created?

I cannot use PowerMock (because of classloaders issues) and I was asked imperatively not to change code in ClassToTest. My testing framework is TestNG if it matters.

Aucun commentaire:

Enregistrer un commentaire