如何从junit执行@After void after(),然后从db-unit执行@ExpectedDatabase?

时间:2017-07-10 14:05:27

标签: unit-testing spring-test dbunit spring-test-dbunit

我想测试一个数据库视图,我使用db-unit将数据插入到测试视图使用的表中,期望值表单视图由db-unit完成,但是这个视图使用一些数据形成另一个视图我想要模拟,我已经做了一些脚本用模拟数据替换视图,完成测试方法后模拟视图被原始视图替换

但我发现问题,@ExpectedDatabase方法后调用了@After void after(),测试失败。

如何从junit执行第一个@After void after(),然后从db-unit执行@ExpectedDatabase

这是我的代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfigTest.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener. DirtiesContextTestExecutionListener.class })
public class ClassTest {

 private static final String MOCK_REOURCE_PATH = "classpath:sql/mock_view.sql";

 private static final String ORIGINAL_REOURCE_PATH = "classpath:sql/original_view.sql";

 @Autowired
 private ApplicationContext applicationContext;

 @Before
 public void init() {
   ScriptUtils.executeSqlScript((DataSource) applicationContext.getBean("dataSource").getConnection(), applicationContext.getReource(MOCK_REOURCE_PATH ));
 }

  @Test
  @DatabaseSetup("classpath:sample-data.xml")
  @ExpectedDatabase(assertionMode = NON_STRICT, value = "classpath:expected-data.xml")
  public void testView() {
  }

  @After
  public void after() {
   ScriptUtils.executeSqlScript((DataSource) applicationContext.getBean("dataSource").getConnection(), applicationContext.getReource(ORIGINAL_REOURCE_PATH ));
  }
}

1 个答案:

答案 0 :(得分:1)

您对TransactionalTestExecutionListener的声明被破坏了:它没有编译"按原样#34;。

确保通过DbUnitTestExecutionListener注册@TestExecutionListeners @Transactional,并使用Spring @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ApplicationConfigTest.class) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class }) @Transactional public class ClassTest { /* ... */ } 注释您的测试类注释,类似于以下内容...

public class BaseClass
{
    public BaseClass(string someValue)
    {
        Console.WriteLine(someValue);
    }
}

public class MyClass : BaseClass
{
    private MyClass(string someValue)
        : base(someValue)
    {
    }

    public static MyClass GetNewInstance(string someValue, bool overrideValue = false)
    {
        if (overrideValue)
        {
            someValue = "42";
        }
        return new MyClass(someValue);
    }
}