Home > Software engineering >  How to initalize spring bean for separation between tests in junit?
How to initalize spring bean for separation between tests in junit?

Time:07-27

I'm using Junit5 and Spring for test. I want to initalize spring bean for each test because I don't want different tests to change the other results of tests.

I'm knowing that a new instance of the test class is created before running each test method by default. under result of test codes is true,because the instance variable number is initalized for each test by junit5.

public class TestInstanceVaribale{
    
    int number = 0;

    @Test
    public void test1() {
        number  = 3;
        Assertions.assertEquals(3, number);
    }
    
    @Test
    public void test2() {
        number  = 5;
        Assertions.assertEquals(5, number);
    }
}

but, this code is failed because spring bean is not initalized.

@Component
public class Car {

    public String name = "myCar";
}
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;

@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class TestSpringVariable {

    @Autowired
    Car car;
    
    @Test
    @Order(1)
    public void test1() {
        car.name = "testCar";
        Assertions.assertEquals("testCar", car.name);
    }
    
    @Test
    @Order(2)
    public void test2() {
        // this is fail. expected: <myCar> but was: <testCar>
        // but I want expected: <myCar> but was: <myCar>
        Assertions.assertEquals("myCar", car.name); 
    }
}

How to initalize spring bean for separation between tests in junit?

@SpringBootTest
@initalizeSpringBeanPerMethod <-- I want like this
public class TestSpringVariable2 {

    @Autowired
    Car car;
    
    @BeforeEach
    public void initalize() { <-- I want like this
        SpirngBean.initalize()
    }
    
}

CodePudding user response:

Take a look at DirtiesContext

Probably adding this to your class should work. It's telling Spring to reset it's state after/before (depending on how you set it) each test

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
  • Related