I have this test:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = Mockito.mock(WorkChronometer.class);
Mockito.when(workChronometer.getAccumulatedMinutes()).thenReturn(120);
Assert.assertEquals(expectedHours, workChronometer.getAccumulatedHours());
}
and the implementation of WorkChronometer:
public class WorkChronometer {
private DateTime startingInstant;
private DateTime stoppingInstant;
private Boolean counting;
//More methods
public Integer getAccumulatedMinutes() {
if (counting)
throw new RuntimeException("Call stopCount first!");
if (startingInstant == null || stoppingInstant == null)
return 0;
return Minutes.minutesBetween(startingInstant, stoppingInstant).getMinutes();
}
public Float getAccumulatedHours() {
Integer accumulatedMinutes = getAccumulatedMinutes();
return accumulatedMinutes / 60f;
}
}
When I execute the test, it fails:
junit.framework.AssertionFailedError: expected:<2.0> but was:<0.0>
But I don't know why. It seems the mock is not returning what I want.
What am I doing wrong?
Thanks.
You're mocking the class under test. Doing that relaces all the methods by methods doing nothing, and returning default values.
If you want to do that, you'll need a spy, or a partial mock.
With a spy:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = new WorkChronometer();
WorkChronometer spy = Mockito.spy(workChronometer);
doReturn(120).when(spy).getAccumulatedMinutes();
Assert.assertEquals(expectedHours, spy.getAccumulatedHours());
}
With a partial mock:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = Mockito.mock(WorkChronometer.class);
Mockito.when(workChronometer.getAccumulatedHours()).thenCallRealMethod();
Mockito.when(workChronometer.getAccumulatedMinutes()).thenReturn(120);
Assert.assertEquals(expectedHours, workChronometer.getAccumulatedHours());
}
Related
I am trying to gather some information after every test method, and would like to analyze the gathered information after the test class completes. So, I have a private member variable, a list which I would like to add to after every test method completes. However, at the end of the day, the member variable always remains null.
Note: My test class implements Callable interface.
Here is my code snippet:
{
private List<String statisticsCollector;
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
this.statisticsCollector = new ArrayList<String>();
}
#Override
public List<String> call() {
log.info("Starting a new thread of execution with Thread# -" + Thread.currentThread().getName());
core.run(this.getClass());
return getStatisticsCollector(); // this is always returing a list of size 0
}
#After
public void gatherSomeStatistics() {
x = x+1;
String sb = new String("Currently executing ----" + x);
log.info("Currently executing ----" + x);
addToStatisticsCollector(sb);
}
#Test
#FileParameters(value = "classpath:folder/testB.json", mapper = MyMapper.class)
public void testB(MarsTestDefinition testDefinition) {
runTests(testDefinition);
}
#Test
#FileParameters(value = "classpath:folder/testA.json", mapper = MyMapper.class)
public void testA(MyDefinition testDefinition) {
runTests(testDefinition);
}
public List<String> getStatisticsCollector() {
return this.statisticsCollector;
}
public void addToStatisticsCollector(String sb) {
this.statisticsCollector.add(sb);
}
}
So, why is it always getting reset, even though I am appending to the list in my #After annotated method?
Any help will be highly appreciated. Thanks
Try with following code, is it working ?
private static List<String> statisticsCollector = new ArrayList<String>();
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
}
public List<String> getStatisticsCollector() {
return statisticsCollector;
}
We have a C# Windows Phone application and I am trying to make use of dbschemaupdater.AddIndex().
However, I am unsure of how to define the fields associated with the index and cannot find any online examples that seem relevant.
Our database tables are defined as classes via SQLMetal, e.g.
[global::System.Data.Linq.Mapping.TableAttribute(Name = "PDA_AppActiveLog")]
public partial class PDA_AppActiveLog : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
[Column(IsVersion = true)]
private Binary version;
private int _AppActiveLogID;
private DateTime _EventTime;
private string _EventCode;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnAppActiveLogIDChanging(int value);
partial void OnAppActiveLogIDChanged();
partial void OnEventTimeChanging(DateTime value);
partial void OnEventTimeChanged();
partial void OnEventCodeChanging(string value);
partial void OnEventCodeChanged();
#endregion
public PDA_AppActiveLog()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_AppActiveLogID", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int AppActiveLogID
{
get
{
return this._AppActiveLogID;
}
set
{
if ((this._AppActiveLogID != value))
{
this.OnAppActiveLogIDChanging(value);
this.SendPropertyChanging();
this._AppActiveLogID = value;
this.SendPropertyChanged("AppActiveLogID");
this.OnAppActiveLogIDChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_EventTime", DbType = "DateTime NOT NULL", CanBeNull = false)]
public DateTime EventTime
{
get
{
return this._EventTime;
}
set
{
if ((this._EventTime != value))
{
this.OnEventTimeChanging(value);
this.SendPropertyChanging();
this._EventTime = value;
this.SendPropertyChanged("EventTime");
this.OnEventTimeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_EventCode", DbType = "NVarChar(30)", UpdateCheck = UpdateCheck.Never, CanBeNull = true)]
public string EventCode
{
get
{
return this._EventCode;
}
set
{
if ((this._EventCode != value))
{
this.OnEventCodeChanging(value);
this.SendPropertyChanging();
this._EventCode = value;
this.SendPropertyChanged("EventCode");
this.OnEventCodeChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Within our code, we add something like:
if (dbSchema.DatabaseSchemaVersion == 8)
{
dbSchema.AddTable<PDA_AppActiveLog>();
dbSchema.DatabaseSchemaVersion = 9;
//dbSchema.AddIndex<PDA_AppActiveLog>("EventCode");
dbSchema.Execute();
dbSchema = dc.CreateDatabaseSchemaUpdater();
}
However, I am unsure how to define which fields belong to the new index.
It seems from this article, that the functionality is there:
http://justinangel.net/AllWp7MangoAPIs#linq2sql
However, all the examples I've seen show the database definition code differently, e.g.:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394022(v=vs.105).aspx#BKMK_Preparingversion3Addinganindexconsideringmultipleupgradepaths
// Index added in version 3 of the application.
[Index(Columns = "Priority", Name = "PriorityIndex")]
I am unsure if I can make equivalent changes, but even if I am, then I can no longer use SQLMetal to pre-generate the classes unless I want to modify them everytime afterwards?
What is the best way to get an index added?
Thanks.
I am working on upgrading our project from .Net 2 to .Net4.5, at the same time I'm pushing as many references as I can to NuGet and making sure the versions are current.
I am having a problem getting one of the tests to run
The Test Classes:
public class Person
{
public static int PersonBaseMethodHitCount { get; set; }
public virtual void BaseMethod()
{
PersonBaseMethodHitCount = PersonBaseMethodHitCount + 1;
}
public static int PersonSomeMethodToBeOverriddenHitCount { get; set; }
public virtual void SomeMethodToBeOverridden()
{
PersonSomeMethodToBeOverriddenHitCount = PersonSomeMethodToBeOverriddenHitCount + 1;
}
}
public class Employee : Person
{
public static int EmployeeSomeMethodToBeOverriddenHitCount { get; set; }
public override void SomeMethodToBeOverridden()
{
EmployeeSomeMethodToBeOverriddenHitCount = EmployeeSomeMethodToBeOverriddenHitCount + 1;
}
public static int EmployeeCannotInterceptHitCount { get; set; }
public void CannotIntercept()
{
EmployeeCannotInterceptHitCount = EmployeeCannotInterceptHitCount + 1;
}
public virtual void MethodWithParameter(
[SuppressMessage("a", "b"), InheritedAttribute, Noninherited]string foo)
{
}
}
public class MyInterceptor : IInterceptor
{
public static int HitCount { get; set; }
public void Intercept(IInvocation invocation)
{
HitCount = HitCount + 1;
invocation.Proceed();
}
}
The test (there is no setup for this fixture):
var container = new WindsorContainer();
container.Register(Component.For<MyInterceptor>().ImplementedBy<MyInterceptor>());
container.Register(
Component
.For<Employee>()
.ImplementedBy<Employee>()
.Interceptors(InterceptorReference.ForType<MyInterceptor>())
.SelectedWith(new DerivedClassMethodsInterceptorSelector()).Anywhere);
container.Register(Classes.FromAssembly(Assembly.GetExecutingAssembly()).Pick().WithService.FirstInterface());
var employee = container.Resolve<Employee>();
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.BaseMethod();
Assert.That(Person.PersonBaseMethodHitCount, Is.EqualTo(1));
// The BaseMethod was not overridden in the derived class so the interceptor should not have been called.
Assert.That(MyInterceptor.HitCount, Is.EqualTo(0));
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.SomeMethodToBeOverridden();
Assert.That(Person.PersonSomeMethodToBeOverriddenHitCount, Is.EqualTo(0));
Assert.That(Employee.EmployeeSomeMethodToBeOverriddenHitCount, Is.EqualTo(1));
Assert.That(MyInterceptor.HitCount, Is.EqualTo(1)); //The test errors out on this line
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.CannotIntercept();
Assert.That(Employee.EmployeeCannotInterceptHitCount, Is.EqualTo(1));
Assert.That(MyInterceptor.HitCount, Is.EqualTo(0));
I added a comment to denote where the test fails.
So far as I can tell the problem is arising in the DerivedClassMethodsInterceptorSelector
Selector:
public class DerivedClassMethodsInterceptorSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
{
return method.DeclaringType != type ? new IInterceptor[0] : interceptors;
}
}
When it makes the comparison of types, the type variable is System.RuntimeType but should be Employee (at least this is my understanding).
EDIT:
This problem was occurring using Castle.Windsor and Castle.Core 3.2.1, After making NuGet install the 3.1.0 package the code works as expected.
I am leaning towards this being a bug, but I could also just be a change in the logic.
I was able to reproduce the same issue with version 3.3.3 with this simple unit test:
[TestClass]
public class MyUnitTest
{
[TestMethod]
public void BasicCase()
{
var ProxyFactory = new ProxyGenerator();
var aopFilters = new IInterceptor[] {new TracingInterceptor()};
var ConcreteType = typeof(MyChild);
var options = new ProxyGenerationOptions { Selector = new AopSelector() };
var proxy = ProxyFactory.CreateClassProxy(ConcreteType, options, aopFilters) as MyChild;
proxy.DoIt();
}
}
public class AopSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type runtimeType, MethodInfo method, IInterceptor[] interceptors)
{
Assert.IsTrue(runtimeType == typeof(MyChild));
return interceptors;
}
}
public class MyWay
{
public virtual void DoIt()
{
Thread.Sleep(200);
}
}
public class MyChild : MyWay
{
public virtual void DoIt2()
{
Thread.Sleep(200);
}
}
public class TracingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var isProperty = invocation.Method.Name.StartsWith("get_")
|| invocation.Method.Name.StartsWith("set_");
if (isProperty)
{
invocation.Proceed();
return;
}
LogMethod(invocation);
}
protected virtual void LogMethod(IInvocation invocation)
{
var target = (invocation.InvocationTarget ?? invocation.Proxy).GetType().Name;
var stopwatch = Stopwatch.StartNew();
try
{
stopwatch.Start();
invocation.Proceed();
}
finally
{
stopwatch.Stop();
var result = stopwatch.ElapsedMilliseconds;
}
}
}
I fixed it by changing Castle's source code and editing method TypeUtil.GetTypeOrNull to look like this:
public static Type GetTypeOrNull(object target)
{
if (target == null)
{
return null;
}
var type = target as Type;
if (type != null)
{
return type;
}
return target.GetType();
}
Of course this is a naive fix, because the problem is somewhere else and it is that instead of an object instance passed to this method, its Type is passed in. However checking if the passed parameter is of type Type and if so returning it instead of calling GetType on it makes it work.
#DataPoints public static final Integer[] input1={1,2};
#Theory
#Test
public void test1(int input1){
}
#DataPoints public static final Integer[] input2={3,4};
#Theory
#Test
public void test2(int input2 ){
}
I want that test1 runs with data set input1 - {1,2} and test2 runs with input2 - {3,4}. But currently each test runs with both the data sets {1,2,3,4}. How to bind specific #DataPoints to specific #Theorys
With JUnit 4.12 (not sure when it was introduced) it is possible to name the DataPoints and assign them to parameters (i learned it from http://farenda.com/junit/junit-theories-with-datapoints/):
#RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
#DataPoints("a values")
public static int[] aValues() {
return new int[]{1, 2};
}
#DataPoints("b values")
public static int[] bValues() {
return new int[]{3, 4};
}
#Theory
public void theoryForA(#FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
#Theory
public void theoryForB(#FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
Output:
TheoryForA called with a = 1
TheoryForA called with a = 2
TheoryForB called with b = 3
TheoryForB called with b = 4
DataPoints apply to the class. If you have a #Theory method which takes an int, and you have a DataPoint which is an array of ints, then it will be called with the int.
#RunWith(Theories.class)
public class TheoryTest {
#DataPoint public static int input1 = 45;
#DataPoint public static int input2 = 46;
#DataPoints public static String[] inputs = new String[] { "foobar", "barbar" };
#Theory public void testString1(String input) {
System.out.println("testString1 input=" + input);
}
#Theory public void testString2(String input) {
System.out.println("testString2 input=" + input);
}
#Theory public void test1(int input) {
System.out.println("test1 input=" + input);
}
#Theory public void test2(int input) {
System.out.println("test2 input=" + input);
}
}
This calls test1 with 45 & 46, and test2 with 45 & 46. It calls testString1 with "foobar" and "barbar" and testString2 with "foobar" and "barbar".
If you really want to use different data sets for different theories, you can wrap the data in a private class:
#RunWith(Theories.class)
public class TheoryTest {
public static class I1 { int i; public I1(int i) { this.i = i;} }
public static class I2 { int i; public I2(int i) { this.i = i;} }
#DataPoint public static I1 input1 = new I1(45);
#DataPoint public static I2 input2 = new I2(46);
#Theory
public void test1(I1 input) {
System.out.println("test1 input=" + input.i);
}
#Theory
public void test2(I2 input) {
System.out.println("test2 input=" + input.i);
}
}
This calls test1 with 45 and test2 with 46. This works, but in my opinion, it obscures the code, and it may be a better solution to just split the Test class into two classes.
In reference to Gábor Lipták's answer, named datapoints can be defined as a static fields (reference) which give us more concise code:
#RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
#DataPoints("a values")
public static int[] aValues = {1, 2};
#DataPoints("b values")
public static int[] bValues = {3, 4};
#Theory
public void theoryForA(#FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
#Theory
public void theoryForB(#FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
Some of the references I have seen talking about using tests for specific values and theories for verifying behavior. As an example, if you have a class that has methods to add and subtract from an attribute, a test would verify correctness of the result (e.g., 1+3 returns 4) whereas a theory might verify that, for the datapoint values (x1, y1), (x2, y2), x+y-y always equals x, x-y+y always equals x, x*y/y always equals x, etc. This way, the results of theories are not coupled as tightly with the data. With theories, you also can filter out cases such as y == 0; they don't count as failure. Bottom line: you can use both. A good paper is: http://web.archive.org/web/20110608210825/http://shareandenjoy.saff.net/tdd-specifications.pdf
I am having trouble implementing a custom cell renderer which will wrap message content when it extends past one line in length. The following is what I have:
public class MessageTable extends JTable
{
private static MessageTable messageTable;
private DefaultTableModel model = new DefaultTableModel();
private String[] emptyData = {};
private TreeMap<Integer, String> messages = null;
public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
this.setText((String)value);
this.setWrapStyleWord(true);
this.setLineWrap(true);
this.setBackground(Color.YELLOW);
int fontHeight = this.getFontMetrics(this.getFont()).getHeight();
int textLength = this.getText().length();
int lines = textLength / this.getColumns() +1;//+1, because we need at least 1 row.
int height = fontHeight * lines;
table.setRowHeight(row, height);
return this;
}
}
public MessageTable()
{
super();
messageTable = this;
this.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
model.addColumn("Message Number", emptyData);
model.addColumn("Message Content", emptyData);
this.setModel(model);
this.setFont(MappingView.theFont);
this.setDefaultRenderer(String.class, new LineWrapCellRenderer());
}
/**
* Set the current messages.
* #param messages
*/
public void setCurrentMessages(TreeMap<Integer, String> messages)
{
clearCurrentMessages();
this.messages = messages;
if (messages != null)
{
for (Integer key : messages.keySet())
{
String[] row = { key.toString(), messages.get(key).toString() };
model.addRow(row);
}
}
}
For some reason, the LineWrapCellRenderer is never used and the rows only ever contain one line of text.
What am I doing wrong?
Your cellrenderer is not used because the default table model returns Object.class for any column (it does not override AbstractTableModel's implementation):
public Class<?> getColumnClass(int columnIndex) {
return Object.class;
}
So either override the method yourself for the model or assign the renderer to Object.class.