vendredi 30 octobre 2015

Spring with JUnit Testing and Dependency Injection does not function

I try to use Springs own Dependency Injection in a Junit test case:

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.binarisinformatik.api.AppConfig;
import org.binarisinformatik.satzrechner.SatzRechner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
//@SpringApplicationConfiguration(classes = {AppConfig.class}) 
public class SatzRechnerTest {

    @Autowired
    private SatzRechner satzRechner;  //SUT

    @Before
    public void setUp() {
    //  AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SatzRechnerTest.class);
        //satzRechner=context.getBean(SatzRechner.class);
    }

    @Test
    public void addiere_satz_4komma6_zu_zahlwert_10() {

        assertThat("Addition von \"4,6\" ergibt nicht 10!",
                satzRechner.summe("4,6"), is(equalTo(10)));
    }

Im testing a class names SatzRechner in which Spring should also autowire some variables. Here is my Class under test:

@Component
public class SatzRechner {

    @Autowired //@Inject
    private Rechner taschenRechner; 
    @Autowired
    private Zahlenfabrik zahlenfabrik;

    public Integer summe(String zeichenSatz) {
        return taschenRechner.summe(zahlenfabrik.erzeugeZahlen(zeichenSatz));
    }
}

And AppConfig.class which is using as Configurationfile looks like that:

@Configuration
@ComponentScan(value={"org.binarisinformatik"})
public class AppConfig {
}

What is here the problem?

Aucun commentaire:

Enregistrer un commentaire