简体   繁体   中英

Change value of guice instance on runtime

I´m using google guice to inject this class example

 class A {
     String a;
 }

Then is injected in my class B

  class B {
     @Inject A aInstance;

     public void checkValue(){
            System.out.println(aInstance.a);
     }   
  }

Maybe using aspectJ, but what I would like is, that one test of mine, would get this A instance and would set the "a" string as "foo", before execute the test that cover the B class, so when the B class invoke checkValue this one would print "foo"

You mention the word test in your question - if you are writing a jUnit test for B you could perform the injection in an @Before clause, as demonstrated here .

private Injector injector;

@Before
public void init() throws Exception {
    injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(A.class).to(MockedInstanceOfAWithValueFoo.class);
        }
    });
}

You could also call

bind(A.class).toInstance(new MockedInstanceOfAWithValueFoo());

If we assume that A has a constructor by which we can define Aa, the mocked instance could look like this:

public class MockedInstanceOfAWithValueFoo extends A{

    public MockedInstanceOfAWithValueFoo() {
        super("foo");
    }

}

Again, you could make your mocked class accept the value of Aa through a constructor to make the creation of B (and the associated value of Aa) more dynamic.

With Mockito:

import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class MyTest {

    @Mock
    A mockA;

    @InjectMocks
    B mockB;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        mockA.a = "Foo";
        //when(mockA.getA()).thenReturn("Foo"); //if you use getter
    }

    @Test
    public void myTest() {
        assertNotNull(mockA);
        assertNotNull(mockA.a);
        assertNotNull(mockB);
        assertNotNull(mockB.ainstance);
        mockB.checkValue();
    }

}

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