I have the following code:
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
#ThreadSafe
public class Aoeu {
#GuardedBy("this")
private long aoeu;
public long getAoeu() {
return aoeu;
}
public void setAoeu(long aoeu) {
this.aoeu = aoeu;
}
}
From what I've read, FindBugs understands the JCiP annotations (indeed, 1.3.9 ships with them) but I don't get any warnings from the above code. According to, I expect to see:
IS: Field not guarded against concurrent access (IS_FIELD_NOT_GUARDED)
This field is annotated with net.jcip.annotations.GuardedBy, but can be accessed in a way that seems to violate the annotation.
Please check below code it shows the bug
class Test
{
#net.jcip.annotations.GuardedBy("this")
private int field;
/**
*
*/
public Test()
{
}
/**
*
*/
public void setField()
{
field++;
}
}
Related
I have a Java/SpringBoot based Kafka Application that consumes from a specific topic. The code is working fine. However, I have to improve the code coverage. There is an abstract class which is not getting covered by the junit
here is the snippet of the abstract class:
public abstract class AbstractEventProcessor<T>{
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractEventProcessor.class)
private KafkaClient kafkaClient;
String topic;
public AbstractEventProcessor(KafkaClient kafkaClient){
this.kafkaClient=kafkaClient;
}
public void abstractEventProcessor(byte[] key, byte[] event, Headers headers){
T message = extractMessage(event);
Store store = extractStore(message);
StoreKey storeKey = null;
private Boolean deadletterFlag = false;
try{
if (Objects.isNull(message) || Object.isNull(store)){
deadletterFlag = true;
return;
}
process(message, store);
} catch (Exception e) {
deadletterFlag=true;
} finally {
if(deadletterFlag){
sendDeadletter(event);
}
}
}
public abstract String getTopicName();
protected abstract void process(T event, Store store);
protected abstract T extractMessage(byte[] messageBytes);
protected abstract Store extractStore(T storeBytes);
private void sendDeadletter(byte[] event){
kafkaClient.publishDeadletter(event);
}
Any help or guidance in unit testing this class using junit / mockito would be great. Thank you
Can someone tell me why XUnit is only recognizing the second constant in the example below? The below code will only run the Theory with the second constant. I'm completely stumped.
namespace DocumentStore.IntegrationTests
{
public static class Constants
{
public const string Test1 = "https://documentstore1.dev.namespace.net/v2/service.svc/basicNoAuth";
public const string Test2 = "https://documentstore1.dev.namespace.net/v2/service.svc";
}
public class Tests
{
[Theory]
[InlineData(Constants.Test1)]
[InlineData(Constants.Test2)]
public void ExampleTest(string url)
{
var test = url;
}
}
}
I also found that if a parameter value is too long xUnit treats the two theories as the same because the truncated values are the same. Super lame but here is a hack I used to get around it. I added a theoryIndex to make sure they are unique
namespace DocumentStore.IntegrationTests
{
public static class Constants
{
public const string Test1 = "https://documentstore1.dev.namespace.net/v2/service.svc/basicNoAuth";
public const string Test2 = "https://documentstore1.dev.namespace.net/v2/service.svc";
}
public class Tests
{
[Theory]
[InlineData(Constants.Test1, 0)]
[InlineData(Constants.Test2, 1)]
public void ExampleTest(string url, int theoryIndex)
{
var test = url;
}
}
}
I am trying to find out whether and how it is possible to nest JUnit test runners, e.g. combine a GuiceJUnitRunner, a Parameterized and a HierarchicalcontextRunner.
To me, it seems that JUnit was not designed to achieve this easily, otherwise BlockJUnit4ClassRunner should have a method which passes the next Runner as an argument.
Someone also implemented a ParallelParameterized runner, which looks to me like combining Parallel and Parameterized was not easily possible.
When googling for "nested" and "JUnit", it comes up with lots of information for nested classes, but I'm looking for nesting Runners, not classes.
There is something called NestedRunner for running plain old Java classes in nested configuration.
your test starts with #RunWith(NestedRunner.class) and here is the example that I found:
#RunWith(NestedRunner.class)
public class ListTest {
// inner class for sharing common context
public class WithArrayList {
// some context for these tests
ArrayList<String> list = new ArrayList<String>();
public class WhenEmpty {
#Test
public void itIsEmpty() {
assertTrue(list.isEmpty());
}
public class AfterAddingAnElement {
// some more context for these tests
String element = "Element";
// you can use instance initializer to initialize your context
// it will be run once per test
{
// the list is still empty in here
assertTrue(list.isEmpty());
list.add(element);
}
#Test
public void itIsNotEmpty() {
assertFalse(list.isEmpty());
}
#Test
public void itContainsTheElement() {
assertTrue(list.contains(element));
}
#Test
public void addingAnotherElementIncreasesSize() {
int sizeBeforeAdding = list.size();
list.add("AnotherElement");
assertThat(list.size(), is(greaterThan(sizeBeforeAdding)));
}
#Test
public void listSizeIsStillOne() {
assertThat(list.size(), is(equalTo(1)));
}
}
#Test
public void isStillEmpty() {
assertTrue(list.isEmpty());
}
}
public class WithTwoElements {
#Before
public void init() {
list.add("Element1");
list.add("Element2");
}
#Test
public void hasSizeOfTwo() {
assertThat(list.size(), is(equalTo(2)));
}
}
}
}
and here is the source for further info
I'm coming from a JUnit background. In the past I've implemented capturing screenshots upon test failure using Rules and TestWatcher interface in Java. Is there something similar in Python?
http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rules/TestWatcher.html
public static class WatchmanTest {
private static String watchedLog;
#Rule
public MethodRule watchman= new TestWatcher() {
#Override
protected void failed(Description d) {
watchedLog+= d + "\n";
}
#Override
protected void succeeded(Description d) {
watchedLog+= d + " " + "success!\n";
}
};
#Test
public void fails() {
fail();
}
#Test
public void succeeds() {
}
}
I found a work around to what I wanted to do by overriding the TestCase.run() method in my BaseTest class.
I got the clue from reason this post which talked about altering the run characteristics by overriding the run method:
PyUnit: stop after first failing test?
I am setting up some MSTest based unit tests. To make my life easier I want to use a base class that handles the generic setup and taredown all of my tests require. My base class looks like this:
[TestClass]
public class DBTestBase {
public TestContext TestContext { get; set; }
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext) {
var config = new XmlConfigurationSource("ARconfig_test.xml");
ActiveRecordStarter.Initialize(Assembly.Load("LocalModels"), config);
}
[TestInitialize()]
public void MyTestInitialize() {
ActiveRecordStarter.CreateSchema();
Before_each_test();
}
protected virtual void Before_each_test() { }
[TestCleanup()]
public void MyTestCleanup() {
After_each_test();
}
protected virtual void After_each_test() { }
}
My actual test class looks like this:
[TestClass]
public class question_tests : DBTestBase {
private void CreateInitialData() {
var question = new Question()
{
Name = "Test Question",
Description = "This is a simple test question"
};
question.Create();
}
protected override void Before_each_test() {
base.Before_each_test();
CreateInitialData();
}
[TestMethod]
public void test_fetching() {
var q = Question.FindAll();
Assert.AreEqual("Test Question", q[0].Name, "Incorrect name.");
}
}
The TestInitialize function works as expected. But the ClassInitialize function never runs. It does run if I add the following to my child class:
[ClassInitialize()]
public static void t(TestContext testContext) {
MyClassInitialize(testContext);
}
Is it possible to get my base class initialize function to run without referencing it in my child class?
ClassInitialize method is executed if and only if the concerned "class" contains at least one TestMethod, and at least one TestMethod from the class is selected for execution.
Confirm this was a problem for me too. I used a constructor on the base and a destructor for the cleanup
[TestClass]
public class question_tests : DBTestBase {
...
[TestCleanup()]
public void TestCleanup()
{
base.MyTestCleanup();
}