@Transactional

时间:2017-10-03 13:45:25

标签: java oracle testing spring-boot junit

我正在为应用程序编写端到端测试。其中一个测试将验证当缺少某些必需的输入时,它将不会将数据持久保存到数据库中。一切都运行良好,直到我决定用@Transactional注释我的测试类,因为我不需要在测试完成后保持结果。在我添加@Transactional注释的那一刻,应用程序突然正常,非null字段为null。

如何设置数据库:

create table MY_TABLE
(
    MY_FIELD VARCHAR(20) NOT NULL
)

相应的型号:

@Entity
@Table(name = "MY_TABLE")
public class MyObject {

    @Column(name = "MY_FIELD", nullable = false)
    private String MyField = null;
}

通过服务层保存:

@Service
public class MyAppServiceImpl implements MyAppService {

    @Inject
    private MyObjectRepository myObjectRepository;  //this interface extends CrudRepository<MyObject , Long>

    @Override
    @Transactional
    public MyObject save(MyObject myObject) {
        return myObjectRepository.save(myObject);
    }
}

在资源层中,myField的值设置为NULL,因此在数据持久化时,我应该收到ORA错误

@Controller
public class MyAppResourceImpl implements MyAppResource {

    @Inject
    private MyAppService myAppService;

    public ResponseEntity doPost(@RequestBody String xml) {
        MyObject myobject = new MyObject();
        myObject.setMyField(null);
        try {
            myAppService.save(myObject);
            return new ResponseEntity(null, HttpStatus.CREATED);
        } catch (SomeExceptions e) {
            return new ResponseEntity("Could not save", HttpStatus.BAD_REQUEST);
        }
    }
}

最后,测试:

@RunWith(SpringRunner.class)
@SpringBootTest
//@Transactional
public class MyAppResourceImplEndToEndTest {
    @Inject
    private MyAppResourceImpl myAppResource;

    @Test
    public void testWithFieldNull() throws Exception {
         ResponseEntity response = myAppResource.doPost("some-xml");
         Assertions.assertThat(response.GetStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
    }
}

此测试按预期工作,但其他测试会将数据保留在数据库中。这不是我想要的行为,所以我用@Transactional注释了测试类。现在没有测试将结果持久化到数据库,但是这个特定的测试方法失败了,因为

Expected :400
Actual   :201

为什么@Transactional注释会突然导致NULL列中保留NOT NULL个值?

0 个答案:

没有答案
相关问题